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(warehouse-sources): implement clay source (#105270)

Daniel RC1b420e406829
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 1990c29b7879..66c67e798bb3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -195,6 +195,7 @@ the row lists both.
| cisco_duo | HTTP | requests (hand-rolled HMAC-SHA1/SHA-512 request signing) | ✅ |
| cloudflare | HTTP | requests | ✅ |
| clari | HTTP | requests | ✅ |
+| clay | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
| clickhouse_cloud | HTTP | requests | ✅ |
@@ -947,7 +948,6 @@ doesn't conflict with concurrent PRs.
- cisco_meraki
- clarifai
- classy
-- clay
- clazar
- cleartax
- clevertap
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clay/clay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/clay.py
new file mode 100644
index 000000000000..b161783d4590
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/clay.py
@@ -0,0 +1,155 @@
+import re
+import dataclasses
+from typing import Any, Optional
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+CLAY_BASE_URL = "https://api.clay.com/public/v0"
+PAGE_SIZE = 100 # API maximum
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Clay table IDs look like `t_0te9i4tZEHwc9hihBXu`, and appear after `/tables/` in table URLs.
+_TABLE_ID_RE = re.compile(r"(?<![A-Za-z0-9_])t_[A-Za-z0-9]+")
+
+
[email protected](frozen=True)
+class ClayResumeConfig:
+ next_cursor: str
+
+
+def parse_table_ids(raw: str) -> list[str]:
+ """Extract unique table IDs, in order, from pasted IDs or table URLs in any separator style."""
+ return list(dict.fromkeys(_TABLE_ID_RE.findall(raw or "")))
+
+
+def flatten_record(record: dict[str, Any]) -> dict[str, Any]:
+ """Turn a record of Clay cells into a flat row.
+
+ Only `success` cells carry a value. Enrichment columns return a structured object in the
+ cell's `fields`, which goes into a sibling `<column>_fields` column so it is not lost. When the
+ table already has a column with that name, the real column wins and the metadata is dropped.
+ """
+ row: dict[str, Any] = {}
+ for name, cell in record.items():
+ if not isinstance(cell, dict) or cell.get("status") != "success":
+ row[name] = None
+ continue
+ row[name] = cell.get("value")
+ fields_column = f"{name}_fields"
+ if cell.get("fields") is not None and fields_column not in record:
+ row[fields_column] = cell["fields"]
+ return row
+
+
+def _query_body(table_id: str, limit: int = PAGE_SIZE) -> dict[str, Any]:
+ # No `select`: the API caps it at 20 fields, and we want every column of the table.
+ return {"query": {"tables": [{"id": table_id}], "field_mode": "names"}, "limit": limit}
+
+
+def clay_source(
+ api_key: str,
+ table_id: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ClayResumeConfig],
+) -> SourceResponse:
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": CLAY_BASE_URL,
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ "auth": {
+ "type": "api_key",
+ "name": "clay-api-key",
+ "api_key": api_key,
+ "location": "header",
+ },
+ },
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": table_id,
+ "table_name": table_id,
+ "write_disposition": "replace",
+ "endpoint": {
+ "method": "POST",
+ "path": "/tables/query",
+ "json": _query_body(table_id),
+ "data_selector": "data",
+ "paginator": JSONResponseCursorPaginator(
+ cursor_path="cursor", cursor_param="cursor", param_location="json"
+ ),
+ },
+ "data_map": flatten_record,
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"cursor": resume_config.next_cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(ClayResumeConfig(next_cursor=str(state["cursor"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ # Rows carry no documented record id or timestamps, so every sync is a full replace. A row
+ # updated while the scan runs can appear twice in that sync.
+ return SourceResponse(name=table_id, items=lambda: resource, primary_keys=None)
+
+
+def validate_credentials(api_key: str, table_ids: list[str]) -> tuple[bool, str | None]:
+ if not table_ids:
+ return False, "Enter at least one Clay table ID or table URL."
+
+ session = make_tracked_session(headers={"clay-api-key": api_key}, redact_values=(api_key,))
+
+ me = session.get(f"{CLAY_BASE_URL}/me", timeout=REQUEST_TIMEOUT_SECONDS)
+ if me.status_code == 401:
+ return False, "Clay rejected the API key. Create a new key under Settings > Account > API keys in Clay."
+ if me.status_code != 200:
+ return (
+ False,
+ f"Clay returned an unexpected status ({me.status_code}) while checking the API key. Try again in a few minutes.",
+ )
+
+ for table_id in table_ids:
+ res = session.post(
+ f"{CLAY_BASE_URL}/tables/query", json=_query_body(table_id, limit=1), timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ if res.status_code == 200:
+ continue
+ if res.status_code == 403:
+ return False, (
+ f"Clay denied access to table {table_id}. Turn on Enable for API in the table's settings "
+ "(Edit table settings > Integrations). This needs a Clay Enterprise plan, and the API key's "
+ "user must have access to the table."
+ )
+ if res.status_code == 404:
+ return False, f"Clay could not find table {table_id}. Check the table ID or URL."
+ return (
+ False,
+ f"Clay returned an unexpected status ({res.status_code}) for table {table_id}. Try again in a few minutes.",
+ )
+
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clay/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/source.py
index b86ce2f41bdf..c1de46289aed 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clay/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/source.py
@@ -1,25 +1,132 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clay.clay import (
+ ClayResumeConfig,
+ clay_source,
+ parse_table_ids,
+ validate_credentials as validate_clay_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
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.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clay import ClaySourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ClaySource(SimpleSource[ClaySourceConfig]):
+class ClaySource(ResumableSource[ClaySourceConfig, ClayResumeConfig]):
+ supported_versions = ("v0",)
+ default_version = "v0"
+ api_docs_url = "https://developers.clay.com/tables"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CLAY
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.clay.com": (
+ "Clay rejected the API key. Create a new key under Settings > Account > API keys in Clay "
+ "and update the source."
+ ),
+ "403 Client Error: Forbidden for url: https://api.clay.com": (
+ "Clay denied access to this table. Turn on Enable for API in the table's settings "
+ "(Edit table settings > Integrations). This needs a Clay Enterprise plan, and the API key's "
+ "user must have access to the table."
+ ),
+ "404 Client Error: Not Found for url: https://api.clay.com": (
+ "Clay could not find this table. It may have been deleted, or the table ID may be wrong."
+ ),
+ }
+
+ def get_schemas(
+ self,
+ config: ClaySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ table_ids = parse_table_ids(config.table_ids)
+ if names is not None:
+ table_ids = [table_id for table_id in table_ids if table_id in names]
+ return [
+ SourceSchema(name=table_id, supports_incremental=False, supports_append=False) for table_id in table_ids
+ ]
+
+ def validate_credentials(
+ self,
+ config: ClaySourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ table_ids = [schema_name] if schema_name else parse_table_ids(config.table_ids)
+ return validate_clay_credentials(config.api_key, table_ids)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ClayResumeConfig]:
+ return ResumableSourceManager[ClayResumeConfig](inputs, ClayResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ClaySourceConfig,
+ resumable_source_manager: ResumableSourceManager[ClayResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return clay_source(
+ api_key=config.api_key,
+ table_id=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.CLAY,
category=DataWarehouseSourceCategory.CRM,
label="Clay",
+ caption=(
+ "Sync rows from your Clay tables. Reading tables through the Clay API needs a Clay Enterprise plan. "
+ "Create an API key in Clay under **Settings > Account > API keys**, and turn on **Enable for API** "
+ "in each table's settings (**Edit table settings > Integrations**). "
+ "Clay's API can't list tables, so paste the ID or URL of each table you want to sync "
+ "(the ID starts with `t_` and appears after `/tables/` in the table's URL)."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/clay",
iconPath="/static/services/clay.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["enrichment", "clay.com"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="table_ids",
+ label="Table IDs or URLs",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="t_0te9i4tZEHwc9hihBXu\nhttps://app.clay.com/workspaces/123/tables/t_...",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clay/tests/test_clay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/tests/test_clay.py
new file mode 100644
index 000000000000..3a179bdebfd2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/tests/test_clay.py
@@ -0,0 +1,169 @@
+import json
+from collections.abc import Iterable
+from typing import Any, Optional, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.clay.clay import (
+ REQUEST_TIMEOUT_SECONDS,
+ ClayResumeConfig,
+ clay_source,
+ flatten_record,
+ parse_table_ids,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+TABLE_ID = "t_0te9i4tZEHwc9hihBXu"
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+ ("raw", "expected"),
+ [
+ (TABLE_ID, [TABLE_ID]),
+ (f"https://app.clay.com/workspaces/123/workbooks/wb_abc/tables/{TABLE_ID}/views/gv_xyz", [TABLE_ID]),
+ (f"{TABLE_ID}, t_second\n t_third\n{TABLE_ID}", [TABLE_ID, "t_second", "t_third"]),
+ ("not a table id", []),
+ ("", []),
+ ],
+)
+def test_parse_table_ids(raw: str, expected: list[str]) -> None:
+ assert parse_table_ids(raw) == expected
+
+
+def test_flatten_record() -> None:
+ record = {
+ "Domain": {"status": "success", "value": "clay.com", "fields": None},
+ "Enrich Company": {"status": "success", "value": "Clay", "fields": {"employee_count": 500}},
+ "Work Email": {"status": "error", "error": "Provider request failed"},
+ "Phone": {"status": "running"},
+ "Notes": {"status": "empty"},
+ "Owner_fields": {"status": "success", "value": "user column", "fields": None},
+ "Owner": {"status": "success", "value": "Ada", "fields": {"title": "CEO"}},
+ }
+
+ assert flatten_record(record) == {
+ "Domain": "clay.com",
+ "Enrich Company": "Clay",
+ "Enrich Company_fields": {"employee_count": 500},
+ "Work Email": None,
+ "Phone": None,
+ "Notes": None,
+ "Owner": "Ada",
+ "Owner_fields": "user column",
+ }
+
+
+class TestClaySourceBehavior:
+ def _drive(
+ self, manager: MagicMock, responses: list[Response]
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], MagicMock]:
+ sent_bodies: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_bodies.append(json.loads(json.dumps(request.json or {})))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = clay_source(
+ api_key="clay_test_key",
+ table_id=TABLE_ID,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ rows = [row for page in cast(Iterable[Any], source_response.items()) for row in page]
+ return sent_bodies, rows, mock_session
+
+ def test_pages_with_body_cursor_and_saves_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(
+ {"data": [{"Domain": {"status": "success", "value": "a.com", "fields": None}}], "cursor": "c1"}
+ ),
+ _make_http_response({"data": [{"Domain": {"status": "success", "value": "b.com", "fields": None}}]}),
+ ]
+ sent_bodies, rows, mock_session = self._drive(manager, responses)
+
+ assert [body.get("cursor") for body in sent_bodies] == [None, "c1"]
+ assert all(
+ body["query"] == {"tables": [{"id": TABLE_ID}], "field_mode": "names"} and body["limit"] == 100
+ for body in sent_bodies
+ )
+ assert rows == [{"Domain": "a.com"}, {"Domain": "b.com"}]
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [ClayResumeConfig(next_cursor="c1")]
+ sent_request = mock_session.send.call_args_list[0].args[0]
+ assert sent_request.method == "POST"
+ assert sent_request.prepare().headers["clay-api-key"] == "clay_test_key"
+ assert all(call.kwargs["timeout"] == REQUEST_TIMEOUT_SECONDS for call in mock_session.send.call_args_list)
+
+ def test_resume_sends_saved_cursor_on_first_request(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ClayResumeConfig(next_cursor="resumed")
+
+ sent_bodies, _, _ = self._drive(manager, [_make_http_response({"data": []})])
+
+ assert [body.get("cursor") for body in sent_bodies] == ["resumed"]
+
+
+ ("me_status", "table_status", "expected_valid", "expected_message_part"),
+ [
+ (200, 200, True, None),
+ (401, None, False, "rejected the API key"),
+ (500, None, False, "unexpected status (500)"),
+ (200, 403, False, "Enterprise plan"),
+ (200, 404, False, "could not find table"),
+ (200, 422, False, "unexpected status (422)"),
+ ],
+)
+def test_validate_credentials(
+ me_status: int, table_status: Optional[int], expected_valid: bool, expected_message_part: Optional[str]
+) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.clay.clay.make_tracked_session"
+ ) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _make_http_response({}, me_status)
+ session.post.return_value = _make_http_response({"data": []}, table_status or 200)
+
+ valid, message = validate_credentials("clay_test_key", [TABLE_ID])
+
+ assert valid is expected_valid
+ if expected_message_part is None:
+ assert message is None
+ else:
+ assert message is not None and expected_message_part in message
+
+
+def test_validate_credentials_requires_a_table_id() -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.clay.clay.make_tracked_session"
+ ) as MockSession:
+ valid, message = validate_credentials("clay_test_key", [])
+
+ assert valid is False
+ assert message == "Enter at least one Clay table ID or table URL."
+ MockSession.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clay/tests/test_clay_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/tests/test_clay_source.py
new file mode 100644
index 000000000000..6c3e86c01007
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clay/tests/test_clay_source.py
@@ -0,0 +1,23 @@
+from typing import Optional
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.clay.source import ClaySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clay import ClaySourceConfig
+
+
+ ("names", "expected"),
+ [
+ (None, ["t_first", "t_second"]),
+ (["t_second"], ["t_second"]),
+ (["t_unknown"], []),
+ ],
+)
+def test_get_schemas_lists_configured_tables(names: Optional[list[str]], expected: list[str]) -> None:
+ config = ClaySourceConfig(api_key="clay_test_key", table_ids="t_first\nhttps://app.clay.com/tables/t_second")
+
+ schemas = ClaySource().get_schemas(config, team_id=1, names=names)
+
+ assert [schema.name for schema in schemas] == expected
+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clay.py
index de85b4aadca4..f54ff9ad5c96 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clay.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clay.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ClaySourceConfig(config.Config):
- pass
+ api_key: str
+ table_ids: str