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(clickup): add time, status-history and custom field tables (#102941)

Tom Owers65ff364a2f06
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 5141436fe4b4..f7b09a003a02 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1567,9 +1567,9 @@ Today (6): `folders`, `goals`, `lists`, `spaces`, `tasks`, `workspaces`
Diffed against: <https://developer.clickup.com/sitemap.xml>
-- [ ] `GET /api/v2/team/{team_id}/time_entries` — tracked time entries - the main quantitative fact table in ClickUp, entirely missing (high)
-- [ ] `GET /api/v2/task/{task_id}/time_in_status (and /api/v2/task/bulk_time_in_status)` — per-task status transition history, the only way to compute cycle time from ClickUp data (high)
-- [ ] `GET /api/v2/list/{list_id}/field (plus folder/space/team available fields)` — custom field definitions that resolve the custom field IDs already embedded in synced tasks (high)
+- [x] `GET /api/v2/team/{team_id}/time_entries` — tracked time entries - the main quantitative fact table in ClickUp, entirely missing (high)
+- [x] `GET /api/v2/task/{task_id}/time_in_status (and /api/v2/task/bulk_time_in_status)` — per-task status transition history, the only way to compute cycle time from ClickUp data (high)
+- [x] `GET /api/v2/list/{list_id}/field (plus folder/space/team available fields)` — custom field definitions that resolve the custom field IDs already embedded in synced tasks (high)
- [ ] `GET /api/v2/task/{task_id}/comment` — task comment stream for collaboration and response-time analysis (medium)
- [ ] `GET /api/v2/team/{team_id}/custom_item` — custom task type lookup resolving the custom_item_id on tasks (medium)
- [ ] `GET /api/v2/space/{space_id}/tag` — space tag lookup resolving the tags attached to tasks (medium)
@@ -1581,6 +1581,7 @@ Diffed against: <https://developer.clickup.com/sitemap.xml>
- [ ] `Docs API (searchdocspublic, getdocpagespublic)` — workspace docs and pages as a content corpus (low)
Note: Diffed against the full operation list in ClickUp's docs sitemap and confirmed the concrete paths by fetching individual reference pages (e.g. /reference/gettimeentrieswithinadaterange -> /api/v2/team/{team_Id}/time_entries). Excluded templates, webhooks, attachments, OAuth and all write operations.
+The chat entry stays open on purpose: those endpoints exist only on ClickUp's v3 API, which this source does not implement, and ClickUp's own chat guide marks them experimental and subject to change at any time.
## Clockify — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/canonical_descriptions.py
index 292ed59286c9..f924aec1333e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/canonical_descriptions.py
@@ -104,4 +104,59 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"color": "The goal's display color.",
},
},
+ "time_entries": {
+ "description": "A tracked block of time, optionally attached to a task, with its duration and billable flag.",
+ "docs_url": "https://developer.clickup.com/reference/gettimeentrieswithinadaterange",
+ "columns": {
+ "id": "Unique identifier for the time entry.",
+ "task": "The task the time was tracked against; absent when the entry is not linked to a task.",
+ "wid": "Identifier of the workspace the entry belongs to.",
+ "user": "The user who tracked the time.",
+ "billable": "Whether the entry is marked billable.",
+ "start": "Time at which tracking started.",
+ "end": "Time at which tracking stopped.",
+ "duration": "Tracked duration in milliseconds; negative while the timer is still running.",
+ "description": "Note recorded on the time entry.",
+ "tags": "Time entry tags applied to the entry.",
+ "source": "Where the entry was created, such as the ClickUp app or an integration.",
+ "at": "Time at which ClickUp last recorded the entry.",
+ "task_location": "Identifiers of the list, folder and space the linked task sits in.",
+ "task_tags": "Tags applied to the linked task.",
+ "task_url": "URL of the linked task in the ClickUp app.",
+ },
+ },
+ "task_time_in_status": {
+ "description": "How long a task has spent in each status, the basis for cycle and lead time.",
+ "docs_url": "https://developer.clickup.com/reference/getbulktaskstimeinstatus",
+ "columns": {
+ "task_id": "Identifier of the task the status history belongs to.",
+ "current_status": "The task's current status, with its color and the total time spent in it so far.",
+ "status_history": "One entry per status the task has held, with the total time spent in each.",
+ },
+ },
+ "custom_fields": {
+ "description": "A Custom Field defined at workspace level, resolving the field IDs carried on tasks.",
+ "docs_url": "https://developer.clickup.com/reference/getteamavailablefields",
+ "columns": {
+ "id": "Unique identifier for the custom field.",
+ "name": "The field's name.",
+ "type": "The field's type, such as drop_down, number, or date.",
+ "type_config": "Type-specific configuration, such as the options of a dropdown field.",
+ "date_created": "Time at which the field was created, as a Unix timestamp in milliseconds.",
+ "hide_from_guests": "Whether the field is hidden from guests.",
+ },
+ },
+ "list_custom_fields": {
+ "description": "A Custom Field accessible to a List, whether defined on the List or inherited from above it.",
+ "docs_url": "https://developer.clickup.com/reference/getaccessiblecustomfields",
+ "columns": {
+ "id": "Unique identifier for the custom field.",
+ "name": "The field's name.",
+ "type": "The field's type, such as drop_down, number, or date.",
+ "type_config": "Type-specific configuration, such as the options of a dropdown field.",
+ "date_created": "Time at which the field was created, as a Unix timestamp in milliseconds.",
+ "hide_from_guests": "Whether the field is hidden from guests.",
+ "_list_id": "Identifier of the list the field is accessible to, injected during the fan-out sync.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/clickup.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/clickup.py
index a5400f60d43e..ac845deb5ddd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/clickup.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/clickup.py
@@ -13,16 +13,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
rest_api_resources,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ create_response_hooks,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
EndpointResource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
CLICKUP_BASE_URL = "https://api.clickup.com/api/v2"
@@ -34,11 +40,33 @@ TASKS_PAGE_SIZE = 100
# 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")
+# Same epoch-millisecond treatment for a time entry's own timestamps.
+TIME_ENTRY_DATE_FIELDS = ("start", "end", "at")
+
+# The time entries endpoint is not paginated: one request returns the whole window, so the window
+# has to stay small enough that a busy workspace's response is still a sane size.
+TIME_ENTRIES_WINDOW_DAYS = 30
+# Where a full refresh starts walking. The endpoint needs an explicit `start_date` (it otherwise
+# answers with just the last 30 days), and ClickUp itself launched in 2017, so no tracked time can
+# predate this.
+TIME_ENTRIES_HISTORY_FLOOR = datetime(2017, 1, 1, tzinfo=UTC)
+
+# Get Bulk Tasks' Time in Status accepts at most 100 task ids per request.
+TIME_IN_STATUS_BATCH_SIZE = 100
+
+# (connect, read) seconds. Left unset, a host that accepts the connection and then stalls holds
+# an import worker open with no bound. The client raises a timeout as retryable, so a stall
+# costs a few bounded attempts instead.
+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)
+
[email protected](frozen=True)
class ClickUpResumeConfig:
# Zero-indexed page of the Get Filtered Team Tasks endpoint to resume from.
- page: int
+ page: int = 0
+ # Epoch-millisecond start of the time entries window to resume from. None means "start from
+ # the beginning of the range this sync covers".
+ window_start: Optional[int] = None
def _get_headers(api_key: str) -> dict[str, str]:
@@ -71,6 +99,13 @@ def _normalize_task(task: dict[str, Any]) -> dict[str, Any]:
return task
+def _normalize_time_entry(entry: dict[str, Any]) -> dict[str, Any]:
+ for date_field in TIME_ENTRY_DATE_FIELDS:
+ if date_field in entry:
+ entry[date_field] = _ms_to_iso(entry[date_field])
+ return entry
+
+
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."""
@@ -158,6 +193,7 @@ def _client_config(api_key: str) -> ClientConfig:
"auth": {"type": "api_key", "api_key": api_key, "name": "Authorization", "location": "header"},
# Every endpoint except tasks returns its whole result in one un-paginated response.
"paginator": SinglePagePaginator(),
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
}
@@ -295,6 +331,202 @@ def _chain_resources(resources: list[Resource]) -> Iterator[list[dict[str, Any]]
yield from resource
+def _make_client(api_key: str) -> RESTClient:
+ """Client for the endpoints whose fan-out or windowing the declarative config can't express."""
+ return RESTClient(
+ base_url=CLICKUP_BASE_URL,
+ headers={"Accept": "application/json"},
+ auth=APIKeyAuth(api_key=api_key, name="Authorization", location="header"),
+ request_timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+
+def _member_user_ids(client: RESTClient, workspace_id: str) -> list[str]:
+ """User ids of every member of the configured workspace.
+
+ Without `assignee`, the time entries endpoint answers with only the calling user's entries, so
+ a workspace-wide table has to name the members. Passing `assignee` needs an owner/admin token;
+ a token without it gets a 403, which `get_non_retryable_errors` reports as a permission problem
+ rather than retrying.
+
+ Raises when the workspace resolves no members. A workspace always holds at least the calling
+ user, so an empty list means the token lost access or the response shape changed. Carrying on
+ without `assignee` would quietly fill the table with one user's time.
+ """
+ user_ids: list[str] = []
+ for page in client.paginate(path="/team", paginator=SinglePagePaginator(), data_selector="teams"):
+ for team in page:
+ if str(team.get("id")) != str(workspace_id):
+ continue
+ for member in team.get("members") or []:
+ user = member.get("user") if isinstance(member.get("user"), dict) else member
+ user_id = user.get("id")
+ if user_id is not None:
+ user_ids.append(str(user_id))
+
+ if not user_ids:
+ raise ValueError(
+ f"ClickUp returned no members for workspace {workspace_id}. "
+ "Check that the API token still has access to the workspace, then sync again."
+ )
+ return user_ids
+
+
+def _epoch_ms(value: datetime) -> int:
+ return round(value.timestamp() * 1000)
+
+
+def _time_entries_range_start(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> datetime:
+ if should_use_incremental_field:
+ millis = _to_epoch_ms(db_incremental_field_last_value)
+ if millis is not None:
+ return datetime.fromtimestamp(millis / 1000, tz=UTC)
+ return TIME_ENTRIES_HISTORY_FLOOR
+
+
+def _time_entry_windows(start: datetime, end: datetime) -> Iterator[SyncWindow[int]]:
+ """Split [start, end] into fixed-length windows, oldest first.
+
+ Consecutive windows share a boundary millisecond, so an entry starting exactly on one is
+ fetched twice; merge on the primary key dedupes it.
+ """
+ cursor = start
+ step = timedelta(days=TIME_ENTRIES_WINDOW_DAYS)
+ while cursor < end:
+ window_end = min(cursor + step, end)
+ yield SyncWindow(start=_epoch_ms(cursor), end=_epoch_ms(window_end))
+ cursor = window_end
+
+
+def _time_entries_rows(
+ api_key: str,
+ workspace_id: str,
+ resumable_source_manager: ResumableSourceManager[ClickUpResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ client = _make_client(api_key)
+
+ params: dict[str, Any] = {
+ "include_task_tags": "true",
+ "include_location_names": "true",
+ "assignee": ",".join(_member_user_ids(client, workspace_id)),
+ }
+
+ start = _time_entries_range_start(should_use_incremental_field, db_incremental_field_last_value)
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.window_start is not None:
+ start = datetime.fromtimestamp(resume.window_start / 1000, tz=UTC)
+
+ for window in _time_entry_windows(start, datetime.now(tz=UTC)):
+ for rows in client.paginate(
+ path=f"/team/{workspace_id}/time_entries",
+ params={**params, "start_date": window.start, "end_date": window.end},
+ paginator=SinglePagePaginator(),
+ data_selector="data",
+ ):
+ if rows:
+ yield [_normalize_time_entry(row) for row in rows]
+ # Checkpoint the window just yielded, not the next one: a crash re-fetches it (merge
+ # dedupes) rather than skipping it.
+ resumable_source_manager.save_state(ClickUpResumeConfig(window_start=window.start))
+
+
+def _all_task_ids(api_key: str, workspace_id: str, team_id: int, job_id: str) -> Iterator[str]:
+ """Every task id in the workspace, for the fan-outs keyed on tasks.
+
+ Deliberately unfiltered by `date_updated_gt`: time in status is a full-refresh table with no
+ timestamp of its own, so bounding the walk would leave older tasks' rows permanently stale.
+ """
+ config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resources": [
+ {
+ "name": "tasks",
+ "endpoint": {
+ "path": f"/team/{workspace_id}/task",
+ "params": {"order_by": "created", "include_closed": "true", "subtasks": "true"},
+ "data_selector": "tasks",
+ "paginator": ClickUpTaskPaginator(),
+ },
+ }
+ ],
+ }
+ for page in rest_api_resource(config, team_id, job_id, None):
+ for task in page:
+ task_id = task.get("id")
+ if task_id is not None:
+ yield str(task_id)
+
+
+def _time_in_status_rows(client: RESTClient, task_ids: list[str]) -> list[dict[str, Any]]:
+ """One row per task from the bulk time-in-status endpoint.
+
+ It answers with a map of task id -> {current_status, status_history} instead of a wrapped
+ array, so there is no data selector to point at. The whole body arrives as a single item and is
+ flattened here into rows carrying the task id the merge key needs.
+ """
+ rows: list[dict[str, Any]] = []
+ for page in client.paginate(
+ path="/task/bulk_time_in_status/task_ids",
+ # `requests` encodes a list as one repeated param per element, which is the format the
+ # endpoint documents (task_ids=3cuh&task_ids=g4fs).
+ params={"task_ids": task_ids},
+ paginator=SinglePagePaginator(),
+ ):
+ for body in page:
+ if not isinstance(body, dict):
+ continue
+ for task_id, time_in_status in body.items():
+ if isinstance(time_in_status, dict):
+ rows.append({"task_id": task_id, **time_in_status})
+ return rows
+
+
+def _task_time_in_status_rows(
+ api_key: str, workspace_id: str, team_id: int, job_id: str
+) -> Iterator[list[dict[str, Any]]]:
+ client = _make_client(api_key)
+ batch: list[str] = []
+ for task_id in _all_task_ids(api_key, workspace_id, team_id, job_id):
+ batch.append(task_id)
+ if len(batch) == TIME_IN_STATUS_BATCH_SIZE:
+ yield _time_in_status_rows(client, batch)
+ batch = []
+ if batch:
+ yield _time_in_status_rows(client, batch)
+
+
+def _list_children_rows(
+ api_key: str, workspace_id: str, resource_path: str, data_key: str, team_id: int, job_id: str
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every list in the workspace and yield rows from a per-list resource.
+
+ Three levels deep (space -> folder -> list -> resource), which the declarative fan-out doesn't
+ cover, and the rows carry no list id of their own, so each is stamped with the list it came
+ from for the composite primary key.
+ """
+ client = _make_client(api_key)
+ # An archived or just-deleted list stops serving its sub-resources; skip it rather than fail
+ # the whole table.
+ hooks = create_response_hooks([{"status_code": 404, "action": "ignore"}], resource_name=data_key)
+
+ for page in _chain_resources(_lists_resources(api_key, workspace_id, team_id, job_id)):
+ for list_row in page:
+ list_id = list_row.get("id")
+ if list_id is None:
+ continue
+ for rows in client.paginate(
+ path=f"/list/{list_id}/{resource_path}",
+ paginator=SinglePagePaginator(),
+ data_selector=data_key,
+ hooks=hooks,
+ ):
+ if rows:
+ yield [{**row, "_list_id": str(list_id)} for row in rows]
+
+
def clickup_source(
api_key: str,
workspace_id: str,
@@ -321,7 +553,10 @@ def clickup_source(
items = lambda: resource
elif config.kind == "workspaces":
resource = rest_api_resource(
- {"client": _client_config(api_key), "resources": [_flat_resource("workspaces", "/team", config.data_key)]},
+ {
+ "client": _client_config(api_key),
+ "resources": [_flat_resource("workspaces", "/team", config.data_key or "")],
+ },
team_id,
job_id,
None,
@@ -330,7 +565,7 @@ def clickup_source(
elif config.kind == "team_scoped":
path = f"/team/{workspace_id}/{config.resource_path}"
resource = rest_api_resource(
- {"client": _client_config(api_key), "resources": [_flat_resource(endpoint, path, config.data_key)]},
+ {"client": _client_config(api_key), "resources": [_flat_resource(endpoint, path, config.data_key or "")]},
team_id,
job_id,
None,
@@ -338,12 +573,26 @@ def clickup_source(
items = lambda: resource
elif config.kind == "space_children":
resource = _space_children_resource(
- api_key, workspace_id, config.resource_path or "", config.data_key, team_id, job_id
+ api_key, workspace_id, config.resource_path or "", config.data_key or "", team_id, job_id
)
items = lambda: resource
elif config.kind == "lists":
list_resources = _lists_resources(api_key, workspace_id, team_id, job_id)
items = lambda: _chain_resources(list_resources)
+ elif config.kind == "list_children":
+ items = lambda: _list_children_rows(
+ api_key, workspace_id, config.resource_path or "", config.data_key or "", team_id, job_id
+ )
+ elif config.kind == "time_entries":
+ items = lambda: _time_entries_rows(
+ api_key,
+ workspace_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.kind == "task_time_in_status":
+ items = lambda: _task_time_in_status_rows(api_key, workspace_id, team_id, job_id)
else:
raise ValueError(f"Unknown ClickUp endpoint kind: {config.kind}")
@@ -351,12 +600,14 @@ def clickup_source(
name=endpoint,
items=items,
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",
+ # Tasks are fetched newest-first (default ClickUp order). Time entries arrive in whatever
+ # order the endpoint chooses within a window, because it documents no sort and takes no
+ # sort param. 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
+ # server filters (`date_updated_gt`, `start_date`/`end_date`), not row ordering, are what
+ # bound each incremental fetch. Live ordering semantics were not verified against the API
+ # as no test credentials were available.
+ sort_mode="desc" if config.kind in ("tasks", "time_entries") else "asc",
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/settings.py
index 32ba0b7bb765..b9722d8f62bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/settings.py
@@ -3,27 +3,44 @@ from typing import Literal, Optional
from products.warehouse_sources.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"]
+# How an endpoint is fetched. Routed on in `clickup.py:clickup_source`.
+# "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
+# "list_children" -> fan-out: every list, then GET /list/{list_id}/<resource>
+# "time_entries" -> GET /team/{workspace_id}/time_entries walked in date windows
+# "task_time_in_status" -> fan-out: every task id, then the bulk time-in-status endpoint
+EndpointKind = Literal[
+ "workspaces",
+ "team_scoped",
+ "tasks",
+ "space_children",
+ "lists",
+ "list_children",
+ "time_entries",
+ "task_time_in_status",
+]
-@dataclass
+@dataclass(frozen=True)
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.
+ # Key the array is wrapped under in the JSON response (e.g. {"spaces": [...]}). None when the
+ # response is not a wrapped array. The bulk time-in-status endpoint answers with a map keyed
+ # by task id, which `clickup.py` reshapes itself.
+ data_key: Optional[str] = None
+ # Resource path segment for team_scoped / space_children / list_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)
+ # Whether the schema picker pre-selects this table. The task and list fan-outs cost one request
+ # per parent on every sync, so they are opt-in rather than on by default.
+ should_sync_default: bool = True
@property
def supports_incremental(self) -> bool:
@@ -79,6 +96,46 @@ CLICKUP_ENDPOINTS: dict[str, ClickUpEndpointConfig] = {
data_key="goals",
primary_keys=["id"],
),
+ "time_entries": ClickUpEndpointConfig(
+ name="time_entries",
+ kind="time_entries",
+ data_key="data",
+ primary_keys=["id"],
+ # `start` is the only timestamp ClickUp's date-range filter bounds, so it is the only field
+ # an incremental sync can advance on. No partitioning: a tracked entry's start can be
+ # edited after the fact, which would move the row's partition and orphan the original.
+ incremental_fields=[
+ {
+ "label": "start",
+ "type": IncrementalFieldType.DateTime,
+ "field": "start",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "task_time_in_status": ClickUpEndpointConfig(
+ name="task_time_in_status",
+ kind="task_time_in_status",
+ primary_keys=["task_id"],
+ should_sync_default=False,
+ ),
+ "custom_fields": ClickUpEndpointConfig(
+ name="custom_fields",
+ kind="team_scoped",
+ resource_path="field",
+ data_key="fields",
+ primary_keys=["id"],
+ ),
+ "list_custom_fields": ClickUpEndpointConfig(
+ name="list_custom_fields",
+ kind="list_children",
+ resource_path="field",
+ data_key="fields",
+ # One row per (list, field): a field defined above the list is accessible to every list
+ # under it, so the field id alone repeats across the table.
+ primary_keys=["_list_id", "id"],
+ should_sync_default=False,
+ ),
}
ENDPOINTS = tuple(CLICKUP_ENDPOINTS.keys())
@@ -86,3 +143,5 @@ ENDPOINTS = tuple(CLICKUP_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in CLICKUP_ENDPOINTS.items()
}
+
+SHOULD_SYNC_DEFAULTS: dict[str, bool] = {name: config.should_sync_default for name, config in CLICKUP_ENDPOINTS.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/source.py
index 1dd5a2157915..01895eeb78ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/source.py
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clickup.cl
from products.warehouse_sources.backend.temporal.data_imports.sources.clickup.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ SHOULD_SYNC_DEFAULTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
@@ -112,8 +113,15 @@ The **Workspace ID** is the numeric ID in your ClickUp URL: `https://app.clickup
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Only tasks exposes an incremental field; ClickUp endpoints are all full-refresh, never append.
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=ENDPOINTS)
+ # Only tasks and time entries expose a server-side timestamp filter; the rest are
+ # full-refresh, and none of them are append-only.
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=ENDPOINTS,
+ should_sync_default=SHOULD_SYNC_DEFAULTS,
+ )
def validate_credentials(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup.py
index caddf5e52189..5665e4f9961e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup.py
@@ -1,5 +1,5 @@
import json
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any
import pytest
@@ -8,9 +8,12 @@ from unittest import mock
from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.clickup.clickup import (
+ TIME_ENTRIES_HISTORY_FLOOR,
+ TIME_IN_STATUS_BATCH_SIZE,
ClickUpResumeConfig,
_ms_to_iso,
_normalize_task,
+ _normalize_time_entry,
_to_epoch_ms,
clickup_source,
validate_credentials,
@@ -60,6 +63,22 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
return snapshots
+def _wire_repeating(session: mock.MagicMock, first: list[Response], then: Any) -> list[dict[str, Any]]:
+ """Like `_wire`, but answers every request past `first` by calling `then()` for a fresh response.
+
+ A full-refresh window walk issues one request per window back to the history floor, far more
+ than a fixed list can hold.
+ """
+ remaining = list(first)
+
+ def _send(*args: Any, **kwargs: Any) -> Response:
+ return remaining.pop(0) if remaining else then()
+
+ snapshots = _wire(session, [])
+ session.send.side_effect = _send
+ return snapshots
+
+
def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
return clickup_source("pk", "9", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)
@@ -225,6 +244,217 @@ class TestTasks:
assert "date_updated_gt" not in snapshots[0]["params"]
+class TestNormalizeTimeEntry:
+ def test_converts_entry_timestamps(self) -> None:
+ entry = _normalize_time_entry(
+ {"id": "4", "start": "1567785250202", "end": "1567785260202", "at": "1567785270202", "duration": "10000"}
+ )
+ assert entry["start"] == "2019-09-06T15:54:10.202000+00:00"
+ assert entry["end"] == "2019-09-06T15:54:20.202000+00:00"
+ assert entry["at"] == "2019-09-06T15:54:30.202000+00:00"
+ # Duration is a millisecond count, not a timestamp, so it must survive untouched.
+ assert entry["duration"] == "10000"
+
+
+class TestTimeEntries:
+ TEAMS = {"teams": [{"id": "9", "members": [{"user": {"id": 11}}, {"user": {"id": 22}}]}]}
+
+ def _entries(self, *ids: str) -> dict[str, Any]:
+ return {"data": [{"id": entry_id, "start": "1567785250202"} for entry_id in ids]}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_windows_from_the_watermark(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ watermark = datetime.now(tz=UTC) - timedelta(days=45)
+ snapshots = _wire(
+ session,
+ [_response(self.TEAMS), _response(self._entries("e1")), _response(self._entries("e2"))],
+ )
+
+ manager = _make_manager()
+ rows = _rows(
+ _source(
+ "time_entries",
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ # Members first, then one request per 30-day window up to now: 45 days spans two.
+ assert [row["id"] for row in rows] == ["e1", "e2"]
+ assert snapshots[0]["url"].endswith("/team")
+ windows = snapshots[1:]
+ assert len(windows) == 2
+ assert all(snapshot["url"].endswith("/team/9/time_entries") for snapshot in windows)
+ assert windows[0]["params"]["start_date"] == round(watermark.timestamp() * 1000)
+ # Windows are contiguous and oldest first, so nothing between them goes unfetched.
+ assert windows[0]["params"]["end_date"] == windows[1]["params"]["start_date"]
+ assert windows[0]["params"]["start_date"] < windows[1]["params"]["start_date"]
+ # Only the workspace's own members are named; `assignee` is what widens the endpoint past
+ # the calling user's own entries.
+ assert windows[0]["params"]["assignee"] == "11,22"
+ assert rows[0]["start"].startswith("2019-09-06T")
+ # Checkpoint the window just yielded, not the next one: a crash re-fetches it and merge
+ # dedupes.
+ saved = [call.args[0].window_start for call in manager.save_state.call_args_list]
+ assert saved == [window["params"]["start_date"] for window in windows]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_the_saved_window(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ resume_start = round((datetime.now(tz=UTC) - timedelta(days=10)).timestamp() * 1000)
+ snapshots = _wire(session, [_response(self.TEAMS), _response(self._entries("e1"))])
+
+ _rows(
+ _source(
+ "time_entries",
+ _make_manager(ClickUpResumeConfig(window_start=resume_start)),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.now(tz=UTC) - timedelta(days=365),
+ )
+ )
+
+ # The saved window wins over the watermark, so a resumed sync doesn't re-walk a year.
+ assert snapshots[1]["params"]["start_date"] == resume_start
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_starts_at_the_history_floor(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire_repeating(session, [_response(self.TEAMS)], lambda: _response({"data": []}))
+
+ _rows(_source("time_entries", _make_manager(), should_use_incremental_field=False))
+
+ # No watermark means the whole history, which the endpoint only returns when asked,
+ # because without an explicit start_date it answers with the last 30 days.
+ assert snapshots[1]["params"]["start_date"] == round(TIME_ENTRIES_HISTORY_FLOOR.timestamp() * 1000)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fails_when_no_members_resolve(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ # A token that can see other workspaces but not the configured one.
+ _wire(session, [_response({"teams": [{"id": "404", "members": [{"user": {"id": 11}}]}]})])
+
+ # Syncing without `assignee` would fill a workspace-wide table with one user's time, and
+ # nothing downstream could tell that from a workspace where only one person tracks time.
+ with pytest.raises(ValueError, match="no members for workspace 9"):
+ _rows(
+ _source(
+ "time_entries",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.now(tz=UTC) - timedelta(days=1),
+ )
+ )
+
+
+class TestTaskTimeInStatus:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_flattens_the_map_into_rows_keyed_by_task(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response({"tasks": [{"id": "t1"}, {"id": "t2"}]}),
+ _response(
+ {
+ "t1": {"current_status": {"status": "open"}, "status_history": []},
+ "t2": {"current_status": {"status": "done"}, "status_history": []},
+ # ClickUp has no wrapper key here, so a stray non-object value would
+ # otherwise be merged into a row.
+ "error": "nope",
+ }
+ ),
+ ],
+ )
+
+ rows = _rows(_source("task_time_in_status", _make_manager()))
+
+ assert [(row["task_id"], row["current_status"]["status"]) for row in rows] == [("t1", "open"), ("t2", "done")]
+ assert snapshots[1]["url"].endswith("/task/bulk_time_in_status/task_ids")
+ assert snapshots[1]["params"]["task_ids"] == ["t1", "t2"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_batches_at_the_endpoint_cap(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ first_batch = [str(i) for i in range(TIME_IN_STATUS_BATCH_SIZE)]
+ snapshots = _wire(
+ session,
+ [
+ _response({"tasks": [{"id": task_id} for task_id in first_batch]}),
+ _response({task_id: {"current_status": {}, "status_history": []} for task_id in first_batch}),
+ _response({"tasks": [{"id": "last"}]}),
+ _response({"last": {"current_status": {}, "status_history": []}}),
+ ],
+ )
+
+ rows = _rows(_source("task_time_in_status", _make_manager()))
+
+ assert len(rows) == TIME_IN_STATUS_BATCH_SIZE + 1
+ # The batch is flushed as soon as it fills, before the next task page is fetched.
+ assert [snapshot["url"].rsplit("/", 1)[-1] for snapshot in snapshots] == [
+ "task",
+ "task_ids",
+ "task",
+ "task_ids",
+ ]
+ assert snapshots[3]["params"]["task_ids"] == ["last"]
+
+
+class TestListChildren:
+ # Two lists reached by both routes: one folderless, one under a folder.
+ LISTS_WALK = [
+ {"spaces": [{"id": "s1"}]},
+ {"lists": [{"id": "l1"}]},
+ {"spaces": [{"id": "s1"}]},
+ {"folders": [{"id": "f1"}]},
+ {"lists": [{"id": "l2"}]},
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stamps_each_field_with_the_list_it_came_from(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ responses = [
+ _response(self.LISTS_WALK[0]),
+ _response(self.LISTS_WALK[1]),
+ _response({"fields": [{"id": "cf1"}]}),
+ _response(self.LISTS_WALK[2]),
+ _response(self.LISTS_WALK[3]),
+ _response(self.LISTS_WALK[4]),
+ _response({"fields": [{"id": "cf1"}, {"id": "cf2"}]}),
+ ]
+ snapshots = _wire(session, responses)
+
+ rows = _rows(_source("list_custom_fields", _make_manager()))
+
+ # A field defined above the list repeats per list, so the row needs the list id the
+ # composite primary key merges on.
+ assert [(row["_list_id"], row["id"]) for row in rows] == [("l1", "cf1"), ("l2", "cf1"), ("l2", "cf2")]
+ assert snapshots[2]["url"].endswith("/list/l1/field")
+ assert snapshots[6]["url"].endswith("/list/l2/field")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_skips_a_list_that_stops_serving_its_fields(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response(self.LISTS_WALK[0]),
+ _response(self.LISTS_WALK[1]),
+ _response({"err": "List not found"}, status_code=404),
+ _response(self.LISTS_WALK[2]),
+ _response(self.LISTS_WALK[3]),
+ _response(self.LISTS_WALK[4]),
+ _response({"fields": [{"id": "cf2"}]}),
+ ],
+ )
+
+ rows = _rows(_source("list_custom_fields", _make_manager()))
+
+ # An archived or deleted list must not take the whole table down with it.
+ assert [(row["_list_id"], row["id"]) for row in rows] == [("l2", "cf2")]
+
+
class TestTeamScoped:
@pytest.mark.parametrize(
"endpoint, expected_path",
@@ -232,12 +462,13 @@ class TestTeamScoped:
("workspaces", "/team"),
("spaces", "/team/9/space"),
("goals", "/team/9/goal"),
+ ("custom_fields", "/team/9/field"),
],
)
@mock.patch(CLIENT_SESSION_PATCH)
def test_team_scoped_endpoints(self, MockSession: mock.MagicMock, endpoint: str, expected_path: str) -> None:
session = MockSession.return_value
- data_key = CLICKUP_ENDPOINTS[endpoint].data_key
+ data_key = CLICKUP_ENDPOINTS[endpoint].data_key or ""
snapshots = _wire(session, [_response({data_key: [{"id": "1"}, {"id": "2"}]})])
rows = _rows(_source(endpoint, _make_manager()))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup_source.py
index d21172738bd9..a1a167ae3c4d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickup/tests/test_clickup_source.py
@@ -44,6 +44,16 @@ class TestClickUpSource:
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"}
+ # Only these two carry a server-side timestamp filter: date_updated_gt on tasks and
+ # start_date/end_date on time entries.
+ assert incremental == {"tasks", "time_entries"}
assert all(schema.supports_append is False for schema in schemas)
+
+ def test_per_parent_fan_outs_are_not_preselected(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ # These two cost a request per task or per list on every sync, so a user opts into them
+ # rather than paying for them by accident.
+ assert schemas["task_time_in_status"].should_sync_default is False
+ assert schemas["list_custom_fields"].should_sync_default is False
+ assert schemas["tasks"].should_sync_default is True