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 clickup import source (#61597)

Tom Owers183559f35f94
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index c98aac96aef1..c106834fdc38 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -59,6 +59,7 @@ the row lists both.
| chartmogul | HTTP | requests | ✅ |
| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
+| clickup | HTTP | requests | ✅ |
| close | HTTP | requests + `rest_source.RESTClient` | ✅ |
| convertkit | HTTP | requests | ✅ |
| convex | HTTP | requests | ✅ |
@@ -172,7 +173,6 @@ doesn't conflict with concurrent PRs.
- box
- braintree
- circleci
-- clickup
- cockroachdb
- confluence
- copper
diff --git a/posthog/temporal/data_imports/sources/clickup/clickup.py b/posthog/temporal/data_imports/sources/clickup/clickup.py
new file mode 100644
index 000000000000..beaf5768d013
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clickup/clickup.py
@@ -0,0 +1,281 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.clickup.settings import CLICKUP_ENDPOINTS
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+CLICKUP_BASE_URL = "https://api.clickup.com/api/v2"
+
+# Get Filtered Team Tasks is the only paginated endpoint; ClickUp caps it at 100 rows/page.
+TASKS_PAGE_SIZE = 100
+# Hard caps to bound fan-out scans; ClickUp workspaces rarely approach these.
+MAX_SPACES = 1000
+MAX_FOLDERS_PER_SPACE = 1000
+
+# ClickUp returns these task timestamps as epoch-milliseconds strings. We normalize them to
+# ISO 8601 so they land as proper datetime columns and can drive partitioning / incremental sync.
+TASK_DATE_FIELDS = ("date_created", "date_updated", "date_closed", "date_done", "start_date", "due_date")
+
+
+class ClickUpRetryableError(Exception):
+ pass
+
+
+class ClickUpResumeConfig:
+ # Zero-indexed page of the Get Filtered Team Tasks endpoint to resume from.
+ page: int
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # ClickUp accepts both personal tokens (pk_...) and OAuth2 access tokens in the raw
+ # Authorization header (no "Bearer" prefix).
+ return {"Authorization": api_key, "Accept": "application/json"}
+
+
+def _ms_to_iso(value: Any) -> Any:
+ """Convert a ClickUp epoch-millisecond timestamp to an ISO 8601 UTC string.
+
+ Returns the original value untouched when it isn't a usable epoch (None, empty, or
+ non-numeric) so we never fabricate timestamps.
+ """
+ if value is None or value == "":
+ return value
+ try:
+ millis = int(value)
+ except (TypeError, ValueError):
+ return value
+ # Build from an exact millisecond timedelta — `fromtimestamp(millis / 1000)` loses
+ # precision in the float division and can land a millisecond off.
+ return (datetime(1970, 1, 1, tzinfo=UTC) + timedelta(milliseconds=millis)).isoformat()
+
+
+def _normalize_task(task: dict[str, Any]) -> dict[str, Any]:
+ for date_field in TASK_DATE_FIELDS:
+ if date_field in task:
+ task[date_field] = _ms_to_iso(task[date_field])
+ return task
+
+
+def _to_epoch_ms(value: Any) -> Optional[int]:
+ """Convert an incremental cursor value (datetime/date/epoch) to epoch milliseconds for
+ ClickUp's date_updated_gt filter."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return round(dt.timestamp() * 1000)
+ if isinstance(value, date):
+ return round(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _build_url(path: str, params: dict[str, Any] | None = None) -> str:
+ url = f"{CLICKUP_BASE_URL}{path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str, workspace_id: str | None) -> tuple[bool, str | None]:
+ """Confirm the token is genuine and (when provided) can see the configured workspace."""
+ try:
+ response = make_tracked_session().get(f"{CLICKUP_BASE_URL}/team", headers=_get_headers(api_key), timeout=10)
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.status_code == 401:
+ return False, "Invalid ClickUp API token"
+ if not response.ok:
+ return False, f"ClickUp API error: {response.status_code} {response.text}"
+
+ if workspace_id:
+ teams = response.json().get("teams", [])
+ if not any(str(team.get("id")) == str(workspace_id) for team in teams):
+ return False, f"Workspace '{workspace_id}' is not accessible with this token"
+
+ return True, None
+
+
+@retry(
+ retry=retry_if_exception_type((ClickUpRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict[str, Any]:
+ response = make_tracked_session().get(url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ClickUpRetryableError(f"ClickUp API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"ClickUp API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _list_space_ids(workspace_id: str, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:
+ spaces = _fetch(_build_url(f"/team/{workspace_id}/space"), headers, logger).get("spaces", [])
+ if len(spaces) >= MAX_SPACES:
+ logger.warning(f"ClickUp: hit space cap ({MAX_SPACES}) for workspace {workspace_id}; some spaces skipped")
+ return [str(space["id"]) for space in spaces[:MAX_SPACES]]
+
+
+def _iter_tasks(
+ workspace_id: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClickUpResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ base_params: dict[str, Any] = {
+ # Order by created (immutable) so pagination stays stable as tasks are updated mid-sync.
+ "order_by": "created",
+ # Closed tasks and subtasks are excluded by default — opt in so we capture everything.
+ "include_closed": "true",
+ "subtasks": "true",
+ }
+ if should_use_incremental_field:
+ cutoff_ms = _to_epoch_ms(db_incremental_field_last_value)
+ if cutoff_ms is not None:
+ base_params["date_updated_gt"] = cutoff_ms
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None else 0
+ if resume is not None:
+ logger.debug(f"ClickUp: resuming tasks from page {page}")
+
+ while True:
+ data = _fetch(_build_url(f"/team/{workspace_id}/task", {**base_params, "page": page}), headers, logger)
+ tasks = data.get("tasks", [])
+ if not tasks:
+ break
+
+ yield [_normalize_task(task) for task in tasks]
+ # Checkpoint the page we just yielded (not the next one): on a crash we re-fetch and
+ # re-yield it, and merge on the primary key dedupes the overlap.
+ resumable_source_manager.save_state(ClickUpResumeConfig(page=page))
+
+ # ClickUp signals the final page either via `last_page` or a short (< page size) page.
+ if data.get("last_page") is True or len(tasks) < TASKS_PAGE_SIZE:
+ break
+ page += 1
+
+
+def _iter_space_children(
+ workspace_id: str, resource_path: str, data_key: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every space in the workspace and yield rows from a per-space resource."""
+ for space_id in _list_space_ids(workspace_id, headers, logger):
+ data = _fetch(_build_url(f"/space/{space_id}/{resource_path}"), headers, logger)
+ rows = data.get(data_key, [])
+ if rows:
+ yield rows
+
+
+def _iter_lists(
+ workspace_id: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ """Lists live in two places: directly under a space (folderless) and under folders."""
+ for space_id in _list_space_ids(workspace_id, headers, logger):
+ folderless = _fetch(_build_url(f"/space/{space_id}/list"), headers, logger).get("lists", [])
+ if folderless:
+ yield folderless
+
+ folders = _fetch(_build_url(f"/space/{space_id}/folder"), headers, logger).get("folders", [])
+ if len(folders) >= MAX_FOLDERS_PER_SPACE:
+ logger.warning(f"ClickUp: hit folder cap ({MAX_FOLDERS_PER_SPACE}) for space {space_id}; some skipped")
+ for folder in folders[:MAX_FOLDERS_PER_SPACE]:
+ folder_lists = _fetch(_build_url(f"/folder/{folder['id']}/list"), headers, logger).get("lists", [])
+ if folder_lists:
+ yield folder_lists
+
+
+def get_rows(
+ api_key: str,
+ workspace_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClickUpResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = CLICKUP_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ if config.kind == "tasks":
+ yield from _iter_tasks(
+ workspace_id,
+ headers,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.kind == "workspaces":
+ rows = _fetch(_build_url("/team"), headers, logger).get(config.data_key, [])
+ if rows:
+ yield rows
+ elif config.kind == "team_scoped":
+ path = f"/team/{workspace_id}/{config.resource_path}"
+ rows = _fetch(_build_url(path), headers, logger).get(config.data_key, [])
+ if rows:
+ yield rows
+ elif config.kind == "space_children":
+ yield from _iter_space_children(workspace_id, config.resource_path or "", config.data_key, headers, logger)
+ elif config.kind == "lists":
+ yield from _iter_lists(workspace_id, headers, logger)
+ else:
+ raise ValueError(f"Unknown ClickUp endpoint kind: {config.kind}")
+
+
+def clickup_source(
+ api_key: str,
+ workspace_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClickUpResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = CLICKUP_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ workspace_id=workspace_id,
+ 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=config.primary_keys,
+ # Tasks are fetched newest-first (default ClickUp order). With sort_mode="desc" the
+ # pipeline only commits the cursor watermark once a sync fully completes, so a mid-sync
+ # crash never advances the cursor past unfetched rows. The `date_updated_gt` server
+ # filter (not row ordering) is what bounds each incremental fetch. Live ordering
+ # semantics were not verified against the API as no test credentials were available.
+ sort_mode="desc" if config.kind == "tasks" else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/clickup/settings.py b/posthog/temporal/data_imports/sources/clickup/settings.py
new file mode 100644
index 000000000000..98c90012e4f5
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clickup/settings.py
@@ -0,0 +1,88 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+# How an endpoint is fetched. Routed on in `clickup.py:get_rows`.
+# "workspaces" -> GET /team (lists the workspaces the token can access)
+# "team_scoped" -> GET /team/{workspace_id}/<resource> returning {data_key: [...]}
+# "tasks" -> GET /team/{workspace_id}/task (page paginated, incremental)
+# "space_children" -> fan-out: list spaces, then GET /space/{space_id}/<resource>
+# "lists" -> fan-out: folderless lists per space + lists per folder
+EndpointKind = Literal["workspaces", "team_scoped", "tasks", "space_children", "lists"]
+
+
+@dataclass
+class ClickUpEndpointConfig:
+ name: str
+ kind: EndpointKind
+ # Key the array is wrapped under in the JSON response (e.g. {"spaces": [...]}).
+ data_key: str
+ primary_keys: list[str]
+ # Resource path segment for team_scoped / space_children endpoints.
+ resource_path: Optional[str] = None
+ # Stable (never-changing) datetime field used for datetime partitioning.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+ @property
+ def supports_incremental(self) -> bool:
+ return len(self.incremental_fields) > 0
+
+
+CLICKUP_ENDPOINTS: dict[str, ClickUpEndpointConfig] = {
+ "workspaces": ClickUpEndpointConfig(
+ name="workspaces",
+ kind="workspaces",
+ data_key="teams",
+ primary_keys=["id"],
+ ),
+ "spaces": ClickUpEndpointConfig(
+ name="spaces",
+ kind="team_scoped",
+ resource_path="space",
+ data_key="spaces",
+ primary_keys=["id"],
+ ),
+ "folders": ClickUpEndpointConfig(
+ name="folders",
+ kind="space_children",
+ resource_path="folder",
+ data_key="folders",
+ primary_keys=["id"],
+ ),
+ "lists": ClickUpEndpointConfig(
+ name="lists",
+ kind="lists",
+ data_key="lists",
+ primary_keys=["id"],
+ ),
+ "tasks": ClickUpEndpointConfig(
+ name="tasks",
+ kind="tasks",
+ data_key="tasks",
+ primary_keys=["id"],
+ partition_key="date_created",
+ incremental_fields=[
+ {
+ "label": "date_updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date_updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "goals": ClickUpEndpointConfig(
+ name="goals",
+ kind="team_scoped",
+ resource_path="goal",
+ data_key="goals",
+ primary_keys=["id"],
+ ),
+}
+
+ENDPOINTS = tuple(CLICKUP_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CLICKUP_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/clickup/source.py b/posthog/temporal/data_imports/sources/clickup/source.py
index 62a611fdbcff..6a82b31b89ac 100644
--- a/posthog/temporal/data_imports/sources/clickup/source.py
+++ b/posthog/temporal/data_imports/sources/clickup/source.py
@@ -1,29 +1,130 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.clickup.clickup import (
+ ClickUpResumeConfig,
+ clickup_source,
+ validate_credentials as validate_clickup_credentials,
+)
+from posthog.temporal.data_imports.sources.clickup.settings import CLICKUP_ENDPOINTS, ENDPOINTS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import ClickUpSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ClickUpSource(SimpleSource[ClickUpSourceConfig]):
+class ClickUpSource(ResumableSource[ClickUpSourceConfig, ClickUpResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CLICKUP
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `workspace_id` selects which ClickUp workspace the stored API token is used against.
+ # Editing it on an existing source must force the token to be re-entered — otherwise an
+ # editor could retarget the preserved token at another workspace it can access.
+ return ["workspace_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CLICK_UP,
label="ClickUp",
- iconPath="/static/services/clickup.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your ClickUp personal API token to pull your ClickUp data into the PostHog Data warehouse.
+
+You can generate a personal token (starts with `pk_`) under **Settings → Apps** in ClickUp.
+
+The **Workspace ID** is the numeric ID in your ClickUp URL: `https://app.clickup.com/{workspace_id}/...`.
+""",
+ iconPath="/static/services/clickup.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/clickup",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="pk_...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="workspace_id",
+ label="Workspace ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="9008123456",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.clickup.com": "Your ClickUp API token is invalid or expired. Please generate a new token and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.clickup.com": "Your ClickUp API token does not have access to this resource. Check the token permissions and try again.",
+ }
+
+ def get_schemas(
+ self,
+ config: ClickUpSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=CLICKUP_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=False,
+ incremental_fields=CLICKUP_ENDPOINTS[endpoint].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: ClickUpSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_clickup_credentials(config.api_key, config.workspace_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ClickUpResumeConfig]:
+ return ResumableSourceManager[ClickUpResumeConfig](inputs, ClickUpResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ClickUpSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ClickUpResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return clickup_source(
+ api_key=config.api_key,
+ workspace_id=config.workspace_id,
+ 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/posthog/temporal/data_imports/sources/clickup/tests/test_clickup.py b/posthog/temporal/data_imports/sources/clickup/tests/test_clickup.py
new file mode 100644
index 000000000000..a38ab06a3b4a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clickup/tests/test_clickup.py
@@ -0,0 +1,274 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.clickup.clickup import (
+ ClickUpResumeConfig,
+ _build_url,
+ _ms_to_iso,
+ _normalize_task,
+ _to_epoch_ms,
+ clickup_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.clickup.settings import CLICKUP_ENDPOINTS, ENDPOINTS
+
+SESSION_PATH = "posthog.temporal.data_imports.sources.clickup.clickup.make_tracked_session"
+
+
+def _make_manager(resume_state: ClickUpResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = 200 <= status_code < 300
+ resp.json.return_value = payload
+ return resp
+
+
+class TestMsToIso:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("1567785250202", "2019-09-06T15:54:10.202000+00:00"),
+ (1567785250202, "2019-09-06T15:54:10.202000+00:00"),
+ (None, None),
+ ("", ""),
+ ("not-a-number", "not-a-number"),
+ ],
+ )
+ def test_ms_to_iso(self, value: Any, expected: Any) -> None:
+ assert _ms_to_iso(value) == expected
+
+
+class TestNormalizeTask:
+ def test_converts_known_date_fields(self) -> None:
+ task = _normalize_task(
+ {"id": "abc", "date_created": "1567785250202", "date_updated": "1567785260202", "name": "Task"}
+ )
+ assert task["date_created"] == "2019-09-06T15:54:10.202000+00:00"
+ assert task["date_updated"] == "2019-09-06T15:54:20.202000+00:00"
+ assert task["name"] == "Task"
+
+ def test_leaves_missing_and_null_fields(self) -> None:
+ task = _normalize_task({"id": "abc", "date_closed": None})
+ assert task["date_closed"] is None
+ assert "due_date" not in task
+
+
+class TestToEpochMs:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (datetime(2019, 9, 6, 15, 54, 10, 202000, tzinfo=UTC), 1567785250202),
+ (datetime(2019, 9, 6, 15, 54, 10, 202000), 1567785250202),
+ (date(2019, 9, 6), 1567728000000),
+ ("1567785250202", 1567785250202),
+ ("nope", None),
+ ],
+ )
+ def test_to_epoch_ms(self, value: Any, expected: Any) -> None:
+ assert _to_epoch_ms(value) == expected
+
+
+class TestBuildUrl:
+ def test_no_params(self) -> None:
+ assert _build_url("/team") == "https://api.clickup.com/api/v2/team"
+
+ def test_encodes_params(self) -> None:
+ url = _build_url("/team/9/task", {"page": 0, "include_closed": "true"})
+ assert url == "https://api.clickup.com/api/v2/team/9/task?page=0&include_closed=true"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(SESSION_PATH)
+ def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected_valid: bool) -> None:
+ mock_session.return_value.get.return_value = _response({"teams": [{"id": "9"}]}, status_code=status_code)
+ valid, _ = validate_credentials("pk_token", workspace_id=None)
+ assert valid is expected_valid
+
+ @mock.patch(SESSION_PATH)
+ def test_workspace_must_be_accessible(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({"teams": [{"id": "9"}]})
+
+ ok, _ = validate_credentials("pk_token", workspace_id="9")
+ assert ok is True
+
+ bad, message = validate_credentials("pk_token", workspace_id="404")
+ assert bad is False
+ assert message is not None and "404" in message
+
+ @mock.patch(SESSION_PATH)
+ def test_request_exception_returns_error(self, mock_session: mock.MagicMock) -> None:
+ import requests
+
+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
+ valid, message = validate_credentials("pk_token", workspace_id=None)
+ assert valid is False
+ assert message == "boom"
+
+
+class TestGetRowsTasks:
+ @mock.patch(SESSION_PATH)
+ def test_paginates_until_short_page(self, mock_session: mock.MagicMock) -> None:
+ full_page = {"tasks": [{"id": str(i), "date_updated": "1567785250202"} for i in range(100)]}
+ short_page = {"tasks": [{"id": "100", "date_updated": "1567785250202"}]}
+ mock_session.return_value.get.side_effect = [_response(full_page), _response(short_page)]
+
+ manager = _make_manager()
+ batches = list(get_rows("pk", "9", "tasks", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_count == 2
+ assert sum(len(b) for b in batches) == 101
+ # date fields normalized to ISO on the way out
+ assert batches[0][0]["date_updated"].startswith("2019-09-06T")
+ # State saved after each yielded page.
+ assert manager.save_state.call_count == 2
+ assert manager.save_state.call_args_list[0].args[0].page == 0
+ assert manager.save_state.call_args_list[1].args[0].page == 1
+
+ @mock.patch(SESSION_PATH)
+ def test_last_page_flag_stops_pagination(self, mock_session: mock.MagicMock) -> None:
+ page = {"tasks": [{"id": str(i)} for i in range(100)], "last_page": True}
+ mock_session.return_value.get.return_value = _response(page)
+
+ list(get_rows("pk", "9", "tasks", mock.MagicMock(), _make_manager()))
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(SESSION_PATH)
+ def test_empty_first_page_yields_nothing(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({"tasks": []})
+ manager = _make_manager()
+
+ batches = list(get_rows("pk", "9", "tasks", mock.MagicMock(), manager))
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(SESSION_PATH)
+ def test_resumes_from_saved_page(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({"tasks": [{"id": "1"}]})
+ manager = _make_manager(ClickUpResumeConfig(page=4))
+
+ list(get_rows("pk", "9", "tasks", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "page=4" in url
+
+ @mock.patch(SESSION_PATH)
+ def test_incremental_adds_date_updated_filter(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({"tasks": [{"id": "1"}]})
+
+ list(
+ get_rows(
+ "pk",
+ "9",
+ "tasks",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2019, 9, 6, 15, 54, 10, 202000, tzinfo=UTC),
+ )
+ )
+
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "date_updated_gt=1567785250202" in url
+
+ @mock.patch(SESSION_PATH)
+ def test_full_refresh_omits_date_filter(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({"tasks": [{"id": "1"}]})
+
+ list(get_rows("pk", "9", "tasks", mock.MagicMock(), _make_manager(), should_use_incremental_field=False))
+
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "date_updated_gt" not in url
+
+
+class TestGetRowsTeamScoped:
+ @pytest.mark.parametrize(
+ "endpoint, expected_path",
+ [
+ ("workspaces", "/team"),
+ ("spaces", "/team/9/space"),
+ ("goals", "/team/9/goal"),
+ ],
+ )
+ @mock.patch(SESSION_PATH)
+ def test_team_scoped_endpoints(self, mock_session: mock.MagicMock, endpoint: str, expected_path: str) -> None:
+ data_key = CLICKUP_ENDPOINTS[endpoint].data_key
+ mock_session.return_value.get.return_value = _response({data_key: [{"id": "1"}, {"id": "2"}]})
+
+ batches = list(get_rows("pk", "9", endpoint, mock.MagicMock(), _make_manager()))
+
+ called_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert called_url.endswith(expected_path)
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]
+
+
+class TestGetRowsFanOut:
+ @mock.patch(SESSION_PATH)
+ def test_folders_fan_out_over_spaces(self, mock_session: mock.MagicMock) -> None:
+ spaces = _response({"spaces": [{"id": "s1"}, {"id": "s2"}]})
+ s1_folders = _response({"folders": [{"id": "f1"}]})
+ s2_folders = _response({"folders": [{"id": "f2"}]})
+ mock_session.return_value.get.side_effect = [spaces, s1_folders, s2_folders]
+
+ batches = list(get_rows("pk", "9", "folders", mock.MagicMock(), _make_manager()))
+
+ assert [item["id"] for batch in batches for item in batch] == ["f1", "f2"]
+
+ @mock.patch(SESSION_PATH)
+ def test_lists_combine_folderless_and_folder_lists(self, mock_session: mock.MagicMock) -> None:
+ spaces = _response({"spaces": [{"id": "s1"}]})
+ folderless = _response({"lists": [{"id": "l1"}]})
+ folders = _response({"folders": [{"id": "f1"}]})
+ folder_lists = _response({"lists": [{"id": "l2"}]})
+ mock_session.return_value.get.side_effect = [spaces, folderless, folders, folder_lists]
+
+ batches = list(get_rows("pk", "9", "lists", mock.MagicMock(), _make_manager()))
+
+ assert [item["id"] for batch in batches for item in batch] == ["l1", "l2"]
+
+
+class TestClickUpSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ config = CLICKUP_ENDPOINTS[endpoint]
+ response = clickup_source("pk", "9", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_tasks_use_desc_sort_mode(self) -> None:
+ assert clickup_source("pk", "9", "tasks", mock.MagicMock(), _make_manager()).sort_mode == "desc"
+
+ def test_non_task_endpoints_use_asc_sort_mode(self) -> None:
+ assert clickup_source("pk", "9", "spaces", mock.MagicMock(), _make_manager()).sort_mode == "asc"
+
+ @pytest.mark.parametrize("config", list(CLICKUP_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config: Any) -> None:
+ if config.partition_key:
+ assert config.partition_key == "date_created"
diff --git a/posthog/temporal/data_imports/sources/clickup/tests/test_clickup_source.py b/posthog/temporal/data_imports/sources/clickup/tests/test_clickup_source.py
new file mode 100644
index 000000000000..af1e45d8848b
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clickup/tests/test_clickup_source.py
@@ -0,0 +1,147 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.clickup.clickup import ClickUpResumeConfig
+from posthog.temporal.data_imports.sources.clickup.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.clickup.source import ClickUpSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import ClickUpSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestClickUpSource:
+ def setup_method(self) -> None:
+ self.source = ClickUpSource()
+ self.team_id = 123
+ self.config = ClickUpSourceConfig(api_key="pk_token", workspace_id="9008123456")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CLICKUP
+
+ def test_workspace_id_is_a_connection_host_field(self) -> None:
+ # Changing the workspace the token targets must re-require the token.
+ assert self.source.connection_host_fields == ["workspace_id"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "ClickUp"
+ assert config.label == "ClickUp"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/clickup.svg"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key", "workspace_id"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ api_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_field.secret is True
+ assert api_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.clickup.com/api/v2/team",
+ "403 Client Error: Forbidden for url: https://api.clickup.com/api/v2/team/9/task",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.clickup.com/api/v2/team",
+ ],
+ )
+ def test_non_retryable_errors_ignore_unrelated(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only tasks expose ClickUp's server-side date_updated_gt filter.
+ assert incremental == {"tasks"}
+ assert all(schema.supports_append is False for schema in schemas)
+
+ def test_tasks_schema_advertises_incremental_field(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["tasks"].incremental_fields == INCREMENTAL_FIELDS["tasks"]
+ assert schemas["spaces"].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tasks"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "tasks"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Invalid ClickUp API token"), False, "Invalid ClickUp API token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.clickup.source.validate_clickup_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key, self.config.workspace_id)
+
+ 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 ClickUpResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.clickup.source.clickup_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_clickup_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "tasks"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1567780450202
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_clickup_source.assert_called_once()
+ kwargs = mock_clickup_source.call_args.kwargs
+ assert kwargs["api_key"] == "pk_token"
+ assert kwargs["workspace_id"] == "9008123456"
+ assert kwargs["endpoint"] == "tasks"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1567780450202
+
+ @mock.patch("posthog.temporal.data_imports.sources.clickup.source.clickup_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_clickup_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "spaces"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1567780450202
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_clickup_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 11bf6dcf775a..c2d2c61941e8 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -259,7 +259,8 @@ class ClickHouseSourceConfig(config.Config):
@config.config
class ClickUpSourceConfig(config.Config):
- pass
+ api_key: str
+ workspace_id: str
@config.config