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 clockify import source (#65628)

Tom Owers27a1fadfff3b
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 6b3444abab15..f866812c4a2a 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -79,6 +79,7 @@ the row lists both.
| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
| clickup | HTTP | requests | ✅ |
+| clockify | HTTP | requests | ✅ |
| close | HTTP | requests + `rest_source.RESTClient` | ✅ |
| convertkit | HTTP | requests | ✅ |
| convex | HTTP | requests | ✅ |
@@ -324,7 +325,6 @@ doesn't conflict with concurrent PRs.
- cisco_meraki
- clarifai
- clazar
-- clockify
- clockodo
- cloudbeds
- coassemble
diff --git a/posthog/temporal/data_imports/sources/clockify/canonical_descriptions.py b/posthog/temporal/data_imports/sources/clockify/canonical_descriptions.py
new file mode 100644
index 000000000000..08eb6620117d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clockify/canonical_descriptions.py
@@ -0,0 +1,100 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Descriptions are sourced from Clockify's public API docs (https://docs.clockify.me/). Partial
+# coverage is fine — anything omitted falls back to LLM enrichment using the docs_url + data types.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "workspaces": {
+ "description": "A Clockify workspace the API key's user belongs to. Workspaces are the top-level container for projects, clients, members, and time entries.",
+ "docs_url": "https://docs.clockify.me/#tag/Workspace",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "name": "Display name of the workspace.",
+ "hourlyRate": "Default hourly rate for the workspace (amount and currency).",
+ "memberships": "The user's membership records within the workspace.",
+ "workspaceSettings": "Workspace-level configuration (time rounding, defaults, feature toggles).",
+ },
+ },
+ "users": {
+ "description": "A member of a workspace. Each row is a user within one workspace (workspace_id + id is unique).",
+ "docs_url": "https://docs.clockify.me/#tag/User",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "workspace_id": "Identifier of the workspace this membership belongs to (added during sync).",
+ "email": "User's email address.",
+ "name": "User's display name.",
+ "activeWorkspace": "Identifier of the user's currently active workspace.",
+ "defaultWorkspace": "Identifier of the user's default workspace.",
+ "status": "Account status within the workspace (e.g. ACTIVE, INACTIVE).",
+ },
+ },
+ "clients": {
+ "description": "A client within a workspace that projects can be billed to.",
+ "docs_url": "https://docs.clockify.me/#tag/Client",
+ "columns": {
+ "id": "Unique identifier for the client.",
+ "workspace_id": "Identifier of the workspace this client belongs to (added during sync).",
+ "workspaceId": "Identifier of the workspace this client belongs to.",
+ "name": "Client name.",
+ "archived": "Whether the client is archived.",
+ },
+ },
+ "projects": {
+ "description": "A project within a workspace. Time entries and tasks are organized under projects.",
+ "docs_url": "https://docs.clockify.me/#tag/Project",
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "workspace_id": "Identifier of the workspace this project belongs to (added during sync).",
+ "workspaceId": "Identifier of the workspace this project belongs to.",
+ "name": "Project name.",
+ "clientId": "Identifier of the client the project is associated with, if any.",
+ "billable": "Whether time logged to the project is billable by default.",
+ "archived": "Whether the project is archived.",
+ "color": "Display color of the project.",
+ "duration": "Total tracked duration on the project (ISO 8601 duration).",
+ },
+ },
+ "tags": {
+ "description": "A tag within a workspace that can be attached to time entries for categorization.",
+ "docs_url": "https://docs.clockify.me/#tag/Tag",
+ "columns": {
+ "id": "Unique identifier for the tag.",
+ "workspace_id": "Identifier of the workspace this tag belongs to (added during sync).",
+ "workspaceId": "Identifier of the workspace this tag belongs to.",
+ "name": "Tag name.",
+ "archived": "Whether the tag is archived.",
+ },
+ },
+ "tasks": {
+ "description": "A task belonging to a project. Each row is a task within one project (workspace_id + project_id + id is unique).",
+ "docs_url": "https://docs.clockify.me/#tag/Task",
+ "columns": {
+ "id": "Unique identifier for the task.",
+ "workspace_id": "Identifier of the workspace this task belongs to (added during sync).",
+ "project_id": "Identifier of the project this task belongs to (added during sync).",
+ "projectId": "Identifier of the project this task belongs to.",
+ "name": "Task name.",
+ "status": "Task status (e.g. ACTIVE, DONE).",
+ "assigneeIds": "Identifiers of the users assigned to the task.",
+ "duration": "Total tracked duration on the task (ISO 8601 duration).",
+ },
+ },
+ "time_entries": {
+ "description": "A logged time entry for a user. Each row is one entry for one user (workspace_id + user_id + id is unique). The nested timeInterval is flattened into time_interval_* columns.",
+ "docs_url": "https://docs.clockify.me/#tag/Time-entry",
+ "columns": {
+ "id": "Unique identifier for the time entry.",
+ "workspace_id": "Identifier of the workspace this entry belongs to (added during sync).",
+ "user_id": "Identifier of the user who logged this entry (added during sync).",
+ "userId": "Identifier of the user who logged this entry.",
+ "workspaceId": "Identifier of the workspace this entry belongs to.",
+ "projectId": "Identifier of the project the entry is logged against, if any.",
+ "taskId": "Identifier of the task the entry is logged against, if any.",
+ "description": "Free-text description of the work.",
+ "billable": "Whether the entry is billable.",
+ "tagIds": "Identifiers of the tags attached to the entry.",
+ "time_interval_start": "Start timestamp of the entry (flattened from timeInterval.start). Used as the incremental cursor and partition key.",
+ "time_interval_end": "End timestamp of the entry (flattened from timeInterval.end); null while the timer is running.",
+ "time_interval_duration": "Duration of the entry as an ISO 8601 duration (flattened from timeInterval.duration).",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/clockify/clockify.py b/posthog/temporal/data_imports/sources/clockify/clockify.py
new file mode 100644
index 000000000000..3aa974fe6c56
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clockify/clockify.py
@@ -0,0 +1,351 @@
+import dataclasses
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime
+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.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.clockify.settings import CLOCKIFY_ENDPOINTS, ClockifyEndpointConfig
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# Global host. Clockify also serves regional hosts (euc1/use2/euw2/apse2); the global host
+# resolves to the user's region, so a single base URL works for every key.
+CLOCKIFY_BASE_URL = "https://api.clockify.me/api/v1"
+
+
+class ClockifyRetryableError(Exception):
+ pass
+
+
+class ClockifyResumeConfig:
+ # The fan-out scope (workspace + optional parent project/user) and the 1-based page we were
+ # reading when the last batch was yielded. Stable ids, not positional indexes, so scopes
+ # added/removed between a crash and the retry can't resume us into the wrong place.
+ workspace_id: str | None = None
+ parent_id: str | None = None
+ page: int = 1
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {"X-Api-Key": api_key, "Accept": "application/json"}
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+def _format_datetime_z(value: Any) -> str:
+ """Format a datetime/date as `yyyy-MM-ddThh:mm:ssZ`, the format Clockify's `start` filter wants."""
+ if isinstance(value, datetime):
+ dt = value
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time())
+ else:
+ # Already a string (e.g. an ISO timestamp persisted as the cursor) — pass through.
+ return str(value)
+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _clamp_future_value_to_now(value: Any) -> Any:
+ """Cap a future datetime cursor at now.
+
+ A future-dated `start` filter would silently match nothing and stall the incremental sync.
+ Asking for entries newer than now is a no-op anyway, so capping keeps the sync self-healing.
+ """
+ now = datetime.now(UTC)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return now if aware > now else value
+ if isinstance(value, date):
+ return now.date() if value > now.date() else value
+ if isinstance(value, str):
+ # The cursor can reach us as an ISO string depending on how it was persisted/deserialised.
+ # Parse it so a future-dated string is clamped too; a non-ISO string passes through.
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return value
+ aware = parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+ return now if aware > now else value
+ return value
+
+
+def validate_credentials(api_key: str) -> bool:
+ """A Clockify API key is user-scoped (no per-endpoint scopes), so one cheap `/user` probe
+ confirms the key is genuine for everything it can reach."""
+ try:
+ response = make_tracked_session().get(f"{CLOCKIFY_BASE_URL}/user", headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type((ClockifyRetryableError, 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, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ """Fetch one page. Clockify list endpoints return a bare JSON array.
+
+ 429s (rate limited; Clockify sends no reset header, so we back off) and 5xx are retried;
+ a non-list body or 4xx auth error is surfaced via `raise_for_status()`.
+ """
+ response = session.get(url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ClockifyRetryableError(f"Clockify API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Clockify API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, list):
+ # Every list endpoint we hit returns an array; a dict here is an unexpected error shape.
+ logger.error(f"Clockify API returned a non-list body: url={url}, body={response.text}")
+ return []
+ return data
+
+
+def _flatten_time_entry(item: dict[str, Any]) -> dict[str, Any]:
+ """Surface the nested `timeInterval` object as top-level columns so the interval start can be
+ used as the incremental cursor and partition key."""
+ interval = item.get("timeInterval")
+ if isinstance(interval, dict):
+ item["time_interval_start"] = interval.get("start")
+ item["time_interval_end"] = interval.get("end")
+ item["time_interval_duration"] = interval.get("duration")
+ return item
+
+
+def _get_item_mapper(endpoint: str) -> Callable[[dict[str, Any]], dict[str, Any]] | None:
+ if endpoint == "time_entries":
+ return _flatten_time_entry
+ return None
+
+
+def _list_ids(
+ session: requests.Session, headers: dict[str, str], base_path: str, page_size: int, logger: FilteringBoundLogger
+) -> Iterator[str]:
+ """Page through a workspace-scoped list endpoint, yielding each row's id. Used to enumerate
+ the parents (projects/users) a two-level fan-out walks over."""
+ page = 1
+ while True:
+ data = _fetch_page(session, _build_url(base_path, {"page": page, "page-size": page_size}), headers, logger)
+ if not data:
+ break
+ for item in data:
+ yield item["id"]
+ if len(data) < page_size:
+ break
+ page += 1
+
+
+def _list_workspace_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:
+ data = _fetch_page(session, f"{CLOCKIFY_BASE_URL}/workspaces", headers, logger)
+ return [workspace["id"] for workspace in data]
+
+
+def _build_scopes(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: ClockifyEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> list[tuple[str, str | None, str]]:
+ """Materialize the (workspace_id, parent_id, full_url) tuples this endpoint iterates.
+
+ Built up front so resume can match the saved scope by id. For single-level fan-out
+ parent_id is None; for two-level fan-out we enumerate the parent endpoint per workspace.
+ """
+ scopes: list[tuple[str, str | None, str]] = []
+ for workspace_id in _list_workspace_ids(session, headers, logger):
+ if config.fan_out_parent is None:
+ scopes.append((workspace_id, None, CLOCKIFY_BASE_URL + config.path.format(workspace_id=workspace_id)))
+ continue
+
+ assert config.parent_id_placeholder is not None # set whenever fan_out_parent is
+ parent_config = CLOCKIFY_ENDPOINTS[config.fan_out_parent]
+ parent_path = CLOCKIFY_BASE_URL + parent_config.path.format(workspace_id=workspace_id)
+ for parent_id in _list_ids(session, headers, parent_path, parent_config.page_size, logger):
+ url = CLOCKIFY_BASE_URL + config.path.format(
+ **{"workspace_id": workspace_id, config.parent_id_placeholder: parent_id}
+ )
+ scopes.append((workspace_id, parent_id, url))
+ return scopes
+
+
+def _find_scope_index(
+ scopes: list[tuple[str, str | None, str]], workspace_id: str | None, parent_id: str | None
+) -> int | None:
+ for index, (scope_workspace_id, scope_parent_id, _url) in enumerate(scopes):
+ if scope_workspace_id == workspace_id and scope_parent_id == parent_id:
+ return index
+ return None
+
+
+def _paginate_scope(
+ session: requests.Session,
+ headers: dict[str, str],
+ base_url: str,
+ config: ClockifyEndpointConfig,
+ batcher: Batcher,
+ manager: ResumableSourceManager[ClockifyResumeConfig],
+ logger: FilteringBoundLogger,
+ mapper: Callable[[dict[str, Any]], dict[str, Any]] | None,
+ workspace_id: str | None,
+ parent_id: str | None,
+ start_page: int,
+ inject: dict[str, str],
+ extra_params: dict[str, Any],
+) -> Iterator[Any]:
+ """Page through one scope, batching rows. Saves resume state AFTER yielding each batch so a
+ crash re-reads the current page (merge dedupes on the primary key) rather than skipping it."""
+ page = start_page
+ while True:
+ params: dict[str, Any] = {"page": page, "page-size": config.page_size, **extra_params}
+ data = _fetch_page(session, _build_url(base_url, params), headers, logger)
+ if not data:
+ break
+
+ for item in data:
+ row = mapper(item) if mapper else item
+ row.update(inject)
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ manager.save_state(ClockifyResumeConfig(workspace_id=workspace_id, parent_id=parent_id, page=page))
+
+ # A short page (fewer rows than asked for) is the last page.
+ if len(data) < config.page_size:
+ break
+ page += 1
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClockifyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = CLOCKIFY_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ session = make_tracked_session()
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ mapper = _get_item_mapper(endpoint)
+
+ # Workspaces is the one non-fan-out endpoint.
+ if not config.workspace_scoped:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_page = resume.page if resume is not None else 1
+ yield from _paginate_scope(
+ session,
+ headers,
+ CLOCKIFY_BASE_URL + config.path,
+ config,
+ batcher,
+ resumable_source_manager,
+ logger,
+ mapper,
+ workspace_id=None,
+ parent_id=None,
+ start_page=start_page,
+ inject={},
+ extra_params={},
+ )
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+ return
+
+ # Server-side incremental filter (time_entries only). `incremental_field` is the user's chosen
+ # cursor; we only have a filter param when the endpoint declares one.
+ extra_params: dict[str, Any] = {}
+ if should_use_incremental_field and db_incremental_field_last_value and config.incremental_param:
+ cursor_value = _clamp_future_value_to_now(db_incremental_field_last_value)
+ extra_params[config.incremental_param] = _format_datetime_z(cursor_value)
+
+ scopes = _build_scopes(session, headers, config, logger)
+
+ # Resolve resume to a starting scope + page. If the bookmarked scope no longer exists, start
+ # from the beginning — merge dedupes the re-pulled rows on the primary key.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_index = 0
+ resume_page = 1
+ if resume is not None:
+ matched = _find_scope_index(scopes, resume.workspace_id, resume.parent_id)
+ if matched is not None:
+ start_index = matched
+ resume_page = resume.page
+ logger.debug(f"Clockify: resuming {endpoint} from scope index {matched}, page {resume_page}")
+
+ for index in range(start_index, len(scopes)):
+ workspace_id, parent_id, url = scopes[index]
+ inject: dict[str, str] = {"workspace_id": workspace_id}
+ if parent_id is not None and config.parent_id_placeholder is not None:
+ inject[config.parent_id_placeholder] = parent_id
+ yield from _paginate_scope(
+ session,
+ headers,
+ url,
+ config,
+ batcher,
+ resumable_source_manager,
+ logger,
+ mapper,
+ workspace_id=workspace_id,
+ parent_id=parent_id,
+ start_page=resume_page if index == start_index else 1,
+ inject=inject,
+ extra_params=extra_params,
+ )
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def clockify_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClockifyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = CLOCKIFY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ 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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/clockify/settings.py b/posthog/temporal/data_imports/sources/clockify/settings.py
new file mode 100644
index 000000000000..dbf1b852b6f3
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clockify/settings.py
@@ -0,0 +1,108 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class ClockifyEndpointConfig:
+ name: str
+ # Path template relative to the API base. Placeholders are filled per fan-out scope:
+ # {workspace_id} for every workspace-scoped endpoint, plus {project_id}/{user_id} for the
+ # two-level fan-out endpoints (tasks/time_entries).
+ path: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ # Stable creation-style field used to partition the Delta table. Never an `updated_at`
+ # style field — those rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
+ # Clockify's max page-size is 5000; 1000 keeps each page well under the response/memory
+ # ceiling while minimizing request count.
+ page_size: int = 1000
+ should_sync_default: bool = True
+ # False only for `/workspaces`, which is the top-level enumeration every other endpoint
+ # fans out over. All other endpoints require a `{workspace_id}` in their path.
+ workspace_scoped: bool = True
+ # For two-level fan-out: the name of the parent endpoint whose ids seed this child's path
+ # (e.g. tasks fan out over `projects`, time_entries over `users`).
+ fan_out_parent: Optional[str] = None
+ # The path placeholder filled with each parent id during a two-level fan-out.
+ parent_id_placeholder: Optional[str] = None
+ # Query param name for the server-side timestamp filter, when the endpoint exposes one.
+ # Only time-entries does (`start` filters entries that started after the given datetime).
+ incremental_param: Optional[str] = None
+
+
+_TIME_ENTRY_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "time_interval_start",
+ "type": IncrementalFieldType.DateTime,
+ "field": "time_interval_start",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+CLOCKIFY_ENDPOINTS: dict[str, ClockifyEndpointConfig] = {
+ # Top-level: the workspaces the API key's user belongs to. Every other endpoint fans out
+ # over these ids. Workspaces are few per user and the endpoint is not paginated.
+ "workspaces": ClockifyEndpointConfig(
+ name="workspaces",
+ path="/workspaces",
+ primary_keys=["id"],
+ workspace_scoped=False,
+ ),
+ "users": ClockifyEndpointConfig(
+ name="users",
+ path="/workspaces/{workspace_id}/users",
+ primary_keys=["workspace_id", "id"],
+ ),
+ "clients": ClockifyEndpointConfig(
+ name="clients",
+ path="/workspaces/{workspace_id}/clients",
+ primary_keys=["workspace_id", "id"],
+ ),
+ "projects": ClockifyEndpointConfig(
+ name="projects",
+ path="/workspaces/{workspace_id}/projects",
+ primary_keys=["workspace_id", "id"],
+ ),
+ "tags": ClockifyEndpointConfig(
+ name="tags",
+ path="/workspaces/{workspace_id}/tags",
+ primary_keys=["workspace_id", "id"],
+ ),
+ # Two-level fan-out: workspace -> project -> tasks. The task id is unique per project, so
+ # the parent ids are part of the primary key to stay unique table-wide.
+ "tasks": ClockifyEndpointConfig(
+ name="tasks",
+ path="/workspaces/{workspace_id}/projects/{project_id}/tasks",
+ primary_keys=["workspace_id", "project_id", "id"],
+ fan_out_parent="projects",
+ parent_id_placeholder="project_id",
+ ),
+ # Two-level fan-out: workspace -> user -> time-entries. The only endpoint with a genuine
+ # server-side time filter (`start`), so the only one that supports incremental sync.
+ # Clockify returns time entries newest-first by start time and exposes no sort param, so
+ # sort_mode is "desc"; the watermark is the (flattened) interval start.
+ "time_entries": ClockifyEndpointConfig(
+ name="time_entries",
+ path="/workspaces/{workspace_id}/user/{user_id}/time-entries",
+ primary_keys=["workspace_id", "user_id", "id"],
+ incremental_fields=_TIME_ENTRY_INCREMENTAL_FIELDS,
+ default_incremental_field="time_interval_start",
+ partition_key="time_interval_start",
+ sort_mode="desc",
+ fan_out_parent="users",
+ parent_id_placeholder="user_id",
+ incremental_param="start",
+ ),
+}
+
+ENDPOINTS = tuple(CLOCKIFY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CLOCKIFY_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/clockify/source.py b/posthog/temporal/data_imports/sources/clockify/source.py
index 9ea6ca4cb257..92226fa09851 100644
--- a/posthog/temporal/data_imports/sources/clockify/source.py
+++ b/posthog/temporal/data_imports/sources/clockify/source.py
@@ -1,20 +1,33 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
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.clockify.clockify import (
+ ClockifyResumeConfig,
+ clockify_source,
+ validate_credentials as validate_clockify_credentials,
+)
+from posthog.temporal.data_imports.sources.clockify.settings import CLOCKIFY_ENDPOINTS, ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
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 ClockifySourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ClockifySource(SimpleSource[ClockifySourceConfig]):
+class ClockifySource(ResumableSource[ClockifySourceConfig, ClockifyResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CLOCKIFY
@@ -25,7 +38,97 @@ class ClockifySource(SimpleSource[ClockifySourceConfig]):
name=SchemaExternalDataSourceType.CLOCKIFY,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Clockify",
- iconPath="/static/services/clockify.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Clockify API key to sync your Clockify data into the PostHog Data warehouse.
+
+You can generate an API key on your [Clockify profile settings](https://app.clockify.me/user/settings) page.
+
+The key is user-scoped — it can read exactly what your Clockify user can. Use an admin or owner key to sync workspace-wide data (projects, clients, every member's time entries).""",
+ iconPath="/static/services/clockify.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/clockify",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # An invalid/revoked key surfaces as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Match the stable status text and base host, not the per-request
+ # path/query. Clockify keys carry no per-endpoint scopes, so a 403 is a credential problem
+ # too (e.g. a non-admin key reaching workspace-wide data).
+ return {
+ "401 Client Error: Unauthorized for url: https://api.clockify.me": "Your Clockify API key is invalid or has been revoked. Generate a new key in your Clockify profile settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.clockify.me": "Your Clockify API key lacks the permissions needed to sync this data. Use an admin or owner key, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.clockify.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ClockifySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ # Only time_entries has a server-side timestamp filter; everything else is full refresh.
+ has_incremental = len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=CLOCKIFY_ENDPOINTS[endpoint].should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: ClockifySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_clockify_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Clockify API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ClockifyResumeConfig]:
+ return ResumableSourceManager[ClockifyResumeConfig](inputs, ClockifyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ClockifySourceConfig,
+ resumable_source_manager: ResumableSourceManager[ClockifyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return clockify_source(
+ api_key=config.api_key,
+ 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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/clockify/tests/test_clockify.py b/posthog/temporal/data_imports/sources/clockify/tests/test_clockify.py
new file mode 100644
index 000000000000..94706727bcb2
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clockify/tests/test_clockify.py
@@ -0,0 +1,321 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.sources.clockify import clockify
+from posthog.temporal.data_imports.sources.clockify.clockify import (
+ CLOCKIFY_BASE_URL,
+ ClockifyResumeConfig,
+ _build_url,
+ _clamp_future_value_to_now,
+ _flatten_time_entry,
+ _format_datetime_z,
+ _get_item_mapper,
+ clockify_source,
+ get_rows,
+)
+from posthog.temporal.data_imports.sources.clockify.settings import CLOCKIFY_ENDPOINTS, ClockifyEndpointConfig
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class TestFormatDatetimeZ:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_datetime_z(value) == expected
+
+ def test_no_plus_zero_offset(self) -> None:
+ assert "+00:00" not in _format_datetime_z(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+
+class TestClampFutureValueToNow:
+ @parameterized.expand(
+ [
+ # Future cursor caps at now; anything at/before now (and non-ISO strings) passes through.
+ ("future_datetime", datetime(2027, 2, 5, tzinfo=UTC), datetime(2026, 6, 15, 12, tzinfo=UTC)),
+ ("past_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)),
+ ("non_iso_string_passthrough", "cursor", "cursor"),
+ ("future_iso_string", "2030-01-01T00:00:00Z", datetime(2026, 6, 15, 12, tzinfo=UTC)),
+ ("past_iso_string", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_clamp(self, _name: str, value: Any, expected: Any) -> None:
+ assert _clamp_future_value_to_now(value) == expected
+
+
+class TestBuildUrl:
+ @parameterized.expand(
+ [
+ ("no_params", f"{CLOCKIFY_BASE_URL}/workspaces", {}, f"{CLOCKIFY_BASE_URL}/workspaces"),
+ ("with_params", "http://x/y", {"page": 1, "page-size": 1000}, "http://x/y?page=1&page-size=1000"),
+ ]
+ )
+ def test_build_url(self, _name: str, base: str, params: dict, expected: str) -> None:
+ assert _build_url(base, params) == expected
+
+
+class TestFlattenTimeEntry:
+ def test_flattens_time_interval(self) -> None:
+ row = _flatten_time_entry(
+ {
+ "id": "T1",
+ "timeInterval": {"start": "2026-03-04T00:00:00Z", "end": "2026-03-04T01:00:00Z", "duration": "PT1H"},
+ }
+ )
+ assert row["time_interval_start"] == "2026-03-04T00:00:00Z"
+ assert row["time_interval_end"] == "2026-03-04T01:00:00Z"
+ assert row["time_interval_duration"] == "PT1H"
+
+ def test_missing_time_interval_is_noop(self) -> None:
+ row = _flatten_time_entry({"id": "T1"})
+ assert "time_interval_start" not in row
+
+ @parameterized.expand([("time_entries", True), ("clients", False), ("workspaces", False)])
+ def test_get_item_mapper(self, endpoint: str, has_mapper: bool) -> None:
+ assert (_get_item_mapper(endpoint) is not None) == has_mapper
+
+
+class _FakeManager(ResumableSourceManager[ClockifyResumeConfig]):
+ """In-memory stand-in: overrides __init__ to skip Redis wiring, records saved state."""
+
+ def __init__(self, state: ClockifyResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[ClockifyResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> ClockifyResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: ClockifyResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class _FakeFetcher:
+ """Stand-in for `_fetch_page` keyed by exact request URL; records every URL fetched."""
+
+ def __init__(self, pages: dict[str, list[dict]]) -> None:
+ self.pages = pages
+ self.urls: list[str] = []
+
+ def __call__(self, session: Any, url: str, headers: dict, logger: Any) -> list[dict]:
+ self.urls.append(url)
+ if url not in self.pages:
+ raise AssertionError(f"Unexpected URL fetched: {url}")
+ return self.pages[url]
+
+
+def _collect(
+ manager: _FakeManager, monkeypatch: Any, fetcher: _FakeFetcher, endpoint: str, **kwargs: Any
+) -> list[dict]:
+ monkeypatch.setattr(clockify, "_fetch_page", fetcher)
+ rows: list[dict] = []
+ for table in get_rows(
+ api_key="key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=manager, **kwargs
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestWorkspacesEndpoint:
+ def test_top_level_pagination_and_no_fan_out(self, monkeypatch: Any) -> None:
+ fetcher = _FakeFetcher(
+ {f"{CLOCKIFY_BASE_URL}/workspaces?page=1&page-size=1000": [{"id": "W1", "name": "A"}, {"id": "W2"}]}
+ )
+ rows = _collect(_FakeManager(), monkeypatch, fetcher, "workspaces")
+ assert [r["id"] for r in rows] == ["W1", "W2"]
+ # Workspaces is its own endpoint — it must NOT also enumerate workspaces for a fan-out.
+ assert fetcher.urls == [f"{CLOCKIFY_BASE_URL}/workspaces?page=1&page-size=1000"]
+
+
+class TestSingleLevelFanOut:
+ def _pages(self) -> dict[str, list[dict]]:
+ return {
+ f"{CLOCKIFY_BASE_URL}/workspaces": [{"id": "W1"}, {"id": "W2"}],
+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/clients?page=1&page-size=1000": [{"id": "C1", "name": "Acme"}],
+ f"{CLOCKIFY_BASE_URL}/workspaces/W2/clients?page=1&page-size=1000": [{"id": "C2"}],
+ }
+
+ def test_fans_out_over_workspaces_and_injects_workspace_id(self, monkeypatch: Any) -> None:
+ rows = _collect(_FakeManager(), monkeypatch, _FakeFetcher(self._pages()), "clients")
+ assert [(r["id"], r["workspace_id"]) for r in rows] == [("C1", "W1"), ("C2", "W2")]
+
+ def test_resume_skips_to_saved_workspace(self, monkeypatch: Any) -> None:
+ manager = _FakeManager(ClockifyResumeConfig(workspace_id="W2", parent_id=None, page=1))
+ rows = _collect(manager, monkeypatch, _FakeFetcher(self._pages()), "clients")
+ # W1 is skipped; only W2's clients are pulled.
+ assert [r["id"] for r in rows] == ["C2"]
+
+ def test_resume_from_missing_workspace_restarts_from_beginning(self, monkeypatch: Any) -> None:
+ manager = _FakeManager(ClockifyResumeConfig(workspace_id="GONE", parent_id=None, page=1))
+ rows = _collect(manager, monkeypatch, _FakeFetcher(self._pages()), "clients")
+ assert [r["id"] for r in rows] == ["C1", "C2"]
+
+
+class TestTwoLevelFanOutTasks:
+ def test_fans_out_workspace_then_project_and_injects_both_ids(self, monkeypatch: Any) -> None:
+ pages = {
+ f"{CLOCKIFY_BASE_URL}/workspaces": [{"id": "W1"}],
+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/projects?page=1&page-size=1000": [{"id": "P1"}, {"id": "P2"}],
+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/projects/P1/tasks?page=1&page-size=1000": [{"id": "TK1"}],
+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/projects/P2/tasks?page=1&page-size=1000": [{"id": "TK2"}],
+ }
+ rows = _collect(_FakeManager(), monkeypatch, _FakeFetcher(pages), "tasks")
+ assert rows == [
+ {"id": "TK1", "workspace_id": "W1", "project_id": "P1"},
+ {"id": "TK2", "workspace_id": "W1", "project_id": "P2"},
+ ]
+
+
+class TestTwoLevelFanOutTimeEntries:
+ def _pages(self) -> dict[str, list[dict]]:
+ return {
+ f"{CLOCKIFY_BASE_URL}/workspaces": [{"id": "W1"}],
+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/users?page=1&page-size=1000": [{"id": "U1"}],
+ }
+
+ def test_flattens_interval_and_injects_workspace_and_user(self, monkeypatch: Any) -> None:
+ pages = self._pages()
+ pages[f"{CLOCKIFY_BASE_URL}/workspaces/W1/user/U1/time-entries?page=1&page-size=1000"] = [
+ {"id": "TE1", "timeInterval": {"start": "2026-03-04T00:00:00Z", "end": None, "duration": None}}
+ ]
+ rows = _collect(_FakeManager(), monkeypatch, _FakeFetcher(pages), "time_entries")
+ assert rows[0]["workspace_id"] == "W1"
+ assert rows[0]["user_id"] == "U1"
+ assert rows[0]["time_interval_start"] == "2026-03-04T00:00:00Z"
+
+ def test_incremental_passes_start_filter(self, monkeypatch: Any) -> None:
+ pages = self._pages()
+ # The exact URL carries the urlencoded `start`; match it by recording fetched URLs instead.
+ fetcher = _FakeFetcher(pages)
+
+ def fetch(session: Any, url: str, headers: dict, logger: Any) -> list[dict]:
+ fetcher.urls.append(url)
+ if "time-entries" in url:
+ return []
+ return pages[url]
+
+ monkeypatch.setattr(clockify, "_fetch_page", fetch)
+ list(
+ get_rows(
+ api_key="key",
+ endpoint="time_entries",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="time_interval_start",
+ )
+ )
+ time_entry_urls = [u for u in fetcher.urls if "time-entries" in u]
+ assert time_entry_urls and "start=2026-03-04T02%3A58%3A14Z" in time_entry_urls[0]
+
+
+class TestPaginateScope:
+ def test_short_page_terminates_pagination(self, monkeypatch: Any) -> None:
+ config = ClockifyEndpointConfig(name="t", path="/p", primary_keys=["id"], page_size=2)
+ # First page returns a full page (2) -> fetch page 2; second returns 1 (< page_size) -> stop.
+ pages = {
+ "http://x/p?page=1&page-size=2": [{"id": "a"}, {"id": "b"}],
+ "http://x/p?page=2&page-size=2": [{"id": "c"}],
+ }
+ fetcher = _FakeFetcher(pages)
+ monkeypatch.setattr(clockify, "_fetch_page", fetcher)
+ batcher = Batcher(logger=MagicMock(), chunk_size=1)
+ manager = _FakeManager()
+ rows: list[dict] = []
+ for table in clockify._paginate_scope(
+ MagicMock(),
+ {},
+ "http://x/p",
+ config,
+ batcher,
+ manager,
+ MagicMock(),
+ None,
+ "W1",
+ None,
+ 1,
+ {"workspace_id": "W1"},
+ {},
+ ):
+ rows.extend(table.to_pylist())
+ if batcher.should_yield(include_incomplete_chunk=True):
+ rows.extend(batcher.get_table().to_pylist())
+ assert [r["id"] for r in rows] == ["a", "b", "c"]
+ assert fetcher.urls == ["http://x/p?page=1&page-size=2", "http://x/p?page=2&page-size=2"]
+
+ def test_saves_state_after_each_yielded_batch(self, monkeypatch: Any) -> None:
+ config = ClockifyEndpointConfig(name="t", path="/p", primary_keys=["id"], page_size=10)
+ pages = {"http://x/p?page=1&page-size=10": [{"id": "a"}, {"id": "b"}]}
+ monkeypatch.setattr(clockify, "_fetch_page", _FakeFetcher(pages))
+ batcher = Batcher(logger=MagicMock(), chunk_size=1) # every row is a full chunk -> yields + saves
+ manager = _FakeManager()
+ list(
+ clockify._paginate_scope(
+ MagicMock(), {}, "http://x/p", config, batcher, manager, MagicMock(), None, "W1", "P1", 1, {}, {}
+ )
+ )
+ # State is saved after each yield, pointing at the page being read so a crash re-reads it.
+ assert manager.saved == [
+ ClockifyResumeConfig(workspace_id="W1", parent_id="P1", page=1),
+ ClockifyResumeConfig(workspace_id="W1", parent_id="P1", page=1),
+ ]
+
+
+class TestClockifySourceResponse:
+ @parameterized.expand([(name,) for name in CLOCKIFY_ENDPOINTS])
+ def test_primary_keys_and_sort_mode_match_config(self, endpoint: str) -> None:
+ response = clockify_source(
+ api_key="key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=_FakeManager()
+ )
+ config = CLOCKIFY_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == config.sort_mode
+
+ def test_time_entries_is_desc_and_partitioned(self) -> None:
+ response = clockify_source(
+ api_key="key", endpoint="time_entries", logger=MagicMock(), resumable_source_manager=_FakeManager()
+ )
+ assert response.sort_mode == "desc"
+ assert response.partition_keys == ["time_interval_start"]
+ assert response.partition_mode == "datetime"
+
+ def test_full_refresh_endpoint_has_no_partition(self) -> None:
+ response = clockify_source(
+ api_key="key", endpoint="clients", logger=MagicMock(), resumable_source_manager=_FakeManager()
+ )
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status,expected", [(200, True), (401, False), (403, False)])
+ def test_status_maps_to_validity(self, status: int, expected: bool, monkeypatch: Any) -> None:
+ response = MagicMock()
+ response.status_code = status
+ session = MagicMock()
+ session.get.return_value = response
+ monkeypatch.setattr(clockify, "make_tracked_session", lambda *a, **k: session)
+ assert clockify.validate_credentials("key") is expected
+
+ def test_network_error_is_invalid(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ monkeypatch.setattr(clockify, "make_tracked_session", lambda *a, **k: session)
+ assert clockify.validate_credentials("key") is False
diff --git a/posthog/temporal/data_imports/sources/clockify/tests/test_clockify_source.py b/posthog/temporal/data_imports/sources/clockify/tests/test_clockify_source.py
new file mode 100644
index 000000000000..af9d58cf7507
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/clockify/tests/test_clockify_source.py
@@ -0,0 +1,158 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from posthog.temporal.data_imports.sources.clockify.clockify import ClockifyResumeConfig
+from posthog.temporal.data_imports.sources.clockify.settings import CLOCKIFY_ENDPOINTS, ENDPOINTS
+from posthog.temporal.data_imports.sources.clockify.source import ClockifySource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import ClockifySourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestClockifySource:
+ def setup_method(self) -> None:
+ self.source = ClockifySource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CLOCKIFY
+
+ def test_source_config_basics(self) -> None:
+ config = self.source.get_source_config
+ assert config.label == "Clockify"
+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+
+ def test_source_config_has_secret_api_key_field(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert len(fields) == 1
+ api_key_field = fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_time_entries_supports_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}
+ for name, schema in schemas.items():
+ expected = name == "time_entries"
+ assert schema.supports_incremental is expected
+ assert schema.supports_append is expected
+
+ def test_time_entries_incremental_field(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}
+ fields = schemas["time_entries"].incremental_fields
+ assert [f["field"] for f in fields] == ["time_interval_start"]
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["clients", "time_entries"])
+ assert {s.name for s in schemas} == {"clients", "time_entries"}
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())
+
+ def test_non_retryable_error_keys_match_clockify_host(self) -> None:
+ # The observed HTTPError message embeds the request URL; the key must match the base host.
+ observed = "401 Client Error: Unauthorized for url: https://api.clockify.me/api/v1/user"
+ assert any(key in observed for key in self.source.get_non_retryable_errors())
+
+ def test_validate_credentials_success(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ "posthog.temporal.data_imports.sources.clockify.source.validate_clockify_credentials",
+ lambda api_key: True,
+ )
+ config = ClockifySourceConfig(api_key="key")
+ assert self.source.validate_credentials(config, self.team_id) == (True, None)
+
+ def test_validate_credentials_failure(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ "posthog.temporal.data_imports.sources.clockify.source.validate_clockify_credentials",
+ lambda api_key: False,
+ )
+ config = ClockifySourceConfig(api_key="bad")
+ valid, error = self.source.validate_credentials(config, self.team_id)
+ assert valid is False
+ assert error is not None
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ClockifyResumeConfig
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ def test_source_for_pipeline_plumbs_endpoint_and_incremental(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> None:
+ captured.update(kwargs)
+
+ monkeypatch.setattr("posthog.temporal.data_imports.sources.clockify.source.clockify_source", fake_source)
+
+ inputs = MagicMock()
+ inputs.schema_name = "time_entries"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-03-04T00:00:00Z"
+ inputs.incremental_field = "time_interval_start"
+ manager = MagicMock()
+
+ self.source.source_for_pipeline(ClockifySourceConfig(api_key="key"), manager, inputs)
+ assert captured["api_key"] == "key"
+ assert captured["endpoint"] == "time_entries"
+ assert captured["should_use_incremental_field"] is True
+ assert captured["db_incremental_field_last_value"] == "2026-03-04T00:00:00Z"
+
+ def test_source_for_pipeline_drops_incremental_value_when_full_refresh(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+ monkeypatch.setattr(
+ "posthog.temporal.data_imports.sources.clockify.source.clockify_source",
+ lambda **kwargs: captured.update(kwargs),
+ )
+
+ inputs = MagicMock()
+ inputs.schema_name = "clients"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(ClockifySourceConfig(api_key="key"), MagicMock(), inputs)
+ assert captured["db_incremental_field_last_value"] is None
+
+
+class TestEndpointConfig:
+ def test_fan_out_children_include_parent_ids_in_primary_key(self) -> None:
+ # Fan-out child ids are unique only within their parent, so the parent id(s) must be part
+ # of the primary key or merges would collapse rows across parents.
+ assert CLOCKIFY_ENDPOINTS["tasks"].primary_keys == ["workspace_id", "project_id", "id"]
+ assert CLOCKIFY_ENDPOINTS["time_entries"].primary_keys == ["workspace_id", "user_id", "id"]
+
+ def test_only_time_entries_has_a_server_side_filter(self) -> None:
+ with_filter = [name for name, cfg in CLOCKIFY_ENDPOINTS.items() if cfg.incremental_param]
+ assert with_filter == ["time_entries"]
+ assert CLOCKIFY_ENDPOINTS["time_entries"].incremental_param == "start"
+
+ def test_partition_keys_are_creation_style_not_updated(self) -> None:
+ for cfg in CLOCKIFY_ENDPOINTS.values():
+ if cfg.partition_key:
+ assert "updated" not in cfg.partition_key
+ assert "last" not in cfg.partition_key.lower()
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index a4412b755336..56554662c64c 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -688,7 +688,7 @@ class ClickUpSourceConfig(config.Config):
@config.config
class ClockifySourceConfig(config.Config):
- pass
+ api_key: str
@config.config