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): add 3 missing tables to the Motion source (#118193)

Tom Owers2067e24fc60a
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 e347ed976e4e..89df95f3514b 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
@@ -8173,9 +8173,9 @@ Today (4): `projects`, `tasks`, `users`, `workspaces`
Diffed against: <https://docs.usemotion.com/api-reference/comments/get/>
-- [ ] `List recurring tasks (GET /v1/recurring-tasks)` — analyze recurring work obligations and assigned workloads that ordinary task records do not fully describe (high)
-- [ ] `Get comments (GET /v1/comments?taskId={taskId})` — track task discussions and collaboration activity with comment creation times and authors (medium)
-- [ ] `Get custom fields (GET /beta/workspaces/{workspaceId}/custom-fields)` — interpret workspace field definitions when reporting on custom task and project values (medium)
+- [x] `List recurring tasks (GET /v1/recurring-tasks)` — analyze recurring work obligations and assigned workloads that ordinary task records do not fully describe (high)
+- [x] `Get comments (GET /v1/comments?taskId={taskId})` — track task discussions and collaboration activity with comment creation times and authors (medium)
+- [x] `Get custom fields (GET /beta/workspaces/{workspaceId}/custom-fields)` — interpret workspace field definitions when reporting on custom task and project values (medium)
Note: Enumerated the official reference navigation and read the recurring task, comment, custom field, and workspace operation pages. Workspace records already include statuses and labels, so those collections are covered as nested data. Comments need task enumeration; recurring tasks and custom fields need workspace enumeration. Excluded write operations and the authenticated user schedule configuration.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/canonical_descriptions.py
index 01321c7d4b02..1d931537dc84 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/canonical_descriptions.py
@@ -59,4 +59,40 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"customFieldValues": "Values of the custom fields defined on the task.",
},
},
+ "recurring_tasks": {
+ "description": "A recurring task template in a Motion workspace, from which Motion creates task instances.",
+ "docs_url": "https://docs.usemotion.com/api-reference/recurring-tasks/get/",
+ "columns": {
+ "id": "Unique identifier for the recurring task.",
+ "workspaceId": "ID of the workspace the recurring task belongs to.",
+ "name": "Recurring task name.",
+ "creator": "User who created the recurring task.",
+ "assignee": "User the recurring task is assigned to.",
+ "project": "Project the recurring task belongs to, when it has one.",
+ "status": "Current status, with whether that status counts as resolved.",
+ "priority": "Priority, such as ASAP, HIGH, MEDIUM, or LOW.",
+ "labels": "Labels applied to the recurring task.",
+ "workspace": "Workspace the recurring task belongs to.",
+ },
+ },
+ "comments": {
+ "description": "A comment on a Motion task.",
+ "docs_url": "https://docs.usemotion.com/api-reference/comments/get/",
+ "columns": {
+ "id": "Unique identifier for the comment.",
+ "taskId": "ID of the task the comment is on.",
+ "content": "HTML content of the comment.",
+ "createdAt": "Date and time the comment was created.",
+ "creator": "User who wrote the comment.",
+ },
+ },
+ "custom_fields": {
+ "description": "A custom field defined in a Motion workspace, which tasks and projects can carry values for.",
+ "docs_url": "https://docs.usemotion.com/api-reference/custom-fields/get/",
+ "columns": {
+ "id": "Unique identifier for the custom field.",
+ "workspaceId": "ID of the workspace the custom field belongs to.",
+ "field": "Type of the custom field, such as text, number, date, select, or person.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/motion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/motion.py
index 7bb4b81c6ce1..78b330d9e6ed 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/motion.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/motion.py
@@ -5,12 +5,19 @@ from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
- rest_api_resource,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ rename_parent_fields,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponseCursorPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.motion.settings import MOTION_ENDPOINTS
@@ -21,23 +28,50 @@ REQUEST_TIMEOUT_SECONDS = 30
@frozen
class MotionResumeConfig:
- cursor: str
+ cursor: Optional[str] = None
+ # Fan-out progress: the parents already done, and the cursor of the one in progress.
+ fanout_state: Optional[dict[str, Any]] = None
def get_resource(endpoint: str) -> EndpointResource:
config = MOTION_ENDPOINTS[endpoint]
- return {
+ parent = config.parent
+ params: dict[str, Any] = dict(config.params)
+ if parent is not None:
+ params[parent.resolve_param] = {"type": "resolve", "resource": parent.name, "field": "id"}
+ endpoint_config: Endpoint = {
+ "data_selector": f"{config.data_key}[*]" if config.data_key else "$",
+ "path": config.path,
+ "params": params,
+ # Explicit, because the framework treats a path that ends in a placeholder as a single
+ # object and would stop a fan-out child after its first page.
+ "paginator": (
+ JSONResponseCursorPaginator(cursor_path="meta.nextCursor", cursor_param="cursor")
+ if config.paginated
+ else SinglePagePaginator()
+ ),
+ }
+ resource: EndpointResource = {
"name": config.name,
"table_name": config.name,
- "primary_key": config.primary_key,
+ "primary_key": config.primary_keys,
"write_disposition": "replace",
- "endpoint": {
- "data_selector": f"{config.data_key}[*]",
- "path": config.path,
- "params": dict(config.params),
- },
+ "endpoint": endpoint_config,
"table_format": "delta",
}
+ if parent is not None:
+ # A parent deleted between the parent listing and its child request has nothing left to sync.
+ endpoint_config["response_actions"] = [{"status_code": 404, "action": "ignore"}]
+ if parent.parent_id_column:
+ resource["include_from_parent"] = ["id"]
+ resource["data_map"] = rename_parent_fields(parent.name, {"id": parent.parent_id_column})
+ return resource
+
+
+def get_resources(endpoint: str) -> list[EndpointResource]:
+ parent = MOTION_ENDPOINTS[endpoint].parent
+ resource = get_resource(endpoint)
+ return [get_resource(parent.name), resource] if parent else [resource]
def motion_source(
@@ -53,26 +87,31 @@ def motion_source(
"client": {
"base_url": MOTION_BASE_URL,
"auth": {"type": "api_key", "api_key": api_key, "name": "X-API-Key", "location": "header"},
- "paginator": JSONResponseCursorPaginator(cursor_path="meta.nextCursor", cursor_param="cursor"),
"request_timeout": REQUEST_TIMEOUT_SECONDS,
},
"resource_defaults": {"write_disposition": "replace"},
- "resources": [get_resource(endpoint)],
+ "resources": list(get_resources(endpoint)),
}
+ is_fanout = endpoint_config.parent is not None
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume_config = resumable_source_manager.load_state()
if resume_config is not None:
- initial_paginator_state = {"cursor": resume_config.cursor}
+ if is_fanout:
+ initial_paginator_state = resume_config.fanout_state
+ elif resume_config.cursor:
+ initial_paginator_state = {"cursor": resume_config.cursor}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- if state and state.get("cursor"):
+ if is_fanout and state is not None:
+ resumable_source_manager.save_state(MotionResumeConfig(fanout_state=state))
+ elif state and state.get("cursor"):
resumable_source_manager.save_state(MotionResumeConfig(cursor=str(state["cursor"])))
elif state is None:
resumable_source_manager.clear_state()
- resource = rest_api_resource(
+ resources = rest_api_resources(
config,
team_id,
job_id,
@@ -80,15 +119,19 @@ def motion_source(
resume_hook=save_checkpoint,
initial_paginator_state=initial_paginator_state,
)
+ resource = next(r for r in resources if r.name == endpoint)
return SourceResponse(
name=endpoint,
items=lambda: resource,
- primary_keys=[endpoint_config.primary_key],
+ primary_keys=endpoint_config.primary_keys,
partition_mode="datetime" if endpoint_config.partition_key else None,
partition_format="month" if endpoint_config.partition_key else None,
partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
column_hints=resource.column_hints,
+ # A fan-out never hands the hook a final None, so its progress would otherwise survive the
+ # run and make the next sync skip every parent it already finished.
+ on_complete=resumable_source_manager.clear_state if is_fanout else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/settings.py
index 68a2962de35f..2dd1469a45ff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/settings.py
@@ -6,16 +6,27 @@ from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField
+@frozen
+class MotionParentConfig:
+ name: str
+ # Placeholder in the child path that takes the `id` of each parent row.
+ resolve_param: str
+ # Column that receives the parent `id`, for child rows that do not carry it themselves.
+ parent_id_column: Optional[str] = None
+
+
@frozen
class MotionEndpointConfig:
name: str
path: str
- # Key the rows sit under in the response envelope, alongside `meta`.
- data_key: str
- primary_key: str = "id"
+ # Key the rows sit under in the response envelope, alongside `meta`. None for a bare array.
+ data_key: Optional[str]
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
# Extra query params sent on every page.
params: dict[str, Any] = field(default_factory=dict)
partition_key: Optional[str] = None
+ paginated: bool = True
+ parent: Optional[MotionParentConfig] = None
MOTION_ENDPOINTS: dict[str, MotionEndpointConfig] = {
@@ -43,6 +54,29 @@ MOTION_ENDPOINTS: dict[str, MotionEndpointConfig] = {
# work would never reach the warehouse.
params={"includeAllStatuses": "true"},
),
+ "recurring_tasks": MotionEndpointConfig(
+ name="recurring_tasks",
+ path="/v1/recurring-tasks?workspaceId={workspaceId}",
+ data_key="tasks",
+ primary_keys=["workspaceId", "id"],
+ parent=MotionParentConfig(name="workspaces", resolve_param="workspaceId", parent_id_column="workspaceId"),
+ ),
+ "comments": MotionEndpointConfig(
+ name="comments",
+ path="/v1/comments?taskId={taskId}",
+ data_key="comments",
+ primary_keys=["taskId", "id"],
+ partition_key="createdAt",
+ parent=MotionParentConfig(name="tasks", resolve_param="taskId"),
+ ),
+ "custom_fields": MotionEndpointConfig(
+ name="custom_fields",
+ path="/beta/workspaces/{workspaceId}/custom-fields",
+ data_key=None,
+ primary_keys=["workspaceId", "id"],
+ paginated=False,
+ parent=MotionParentConfig(name="workspaces", resolve_param="workspaceId", parent_id_column="workspaceId"),
+ ),
}
ENDPOINTS = tuple(MOTION_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/source.py
index 7429aa34750c..c0272da18f7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/source.py
@@ -58,11 +58,11 @@ class MotionSource(ResumableSource[MotionSourceConfig, MotionResumeConfig]):
name=ExternalDataSourceType.MOTION,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Motion",
- caption="""Enter your Motion API key to sync your workspaces, users, projects, and tasks into the PostHog Data warehouse.
+ caption="""Enter your Motion API key to sync your workspaces, users, projects, tasks, recurring tasks, comments, and custom fields into the PostHog Data warehouse.
Create an API key in Motion under Settings, then API. Motion shows the key once, so copy it before closing the dialog.
-Motion rate limits API keys, and individual accounts get a much smaller allowance than teams, so a first sync of a large workspace can take a while.""",
+Motion rate limits API keys, and individual accounts get a much smaller allowance than teams, so a first sync of a large workspace can take a while. The comments table makes one request for each task, so it is the slowest table to sync.""",
iconPath="/static/services/motion.png",
docsUrl="https://posthog.com/docs/cdp/sources/motion",
keywords=["usemotion", "calendar", "tasks"],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/tests/test_motion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/tests/test_motion.py
index 59a79a343442..7aec26aa28f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motion/tests/test_motion.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motion/tests/test_motion.py
@@ -1,9 +1,11 @@
+from collections.abc import Callable
from typing import Any, Optional
import pytest
from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ RecordedRequest,
ScriptedResponse,
SourceDriver,
always,
@@ -27,6 +29,34 @@ def _manager(resume_state: MotionResumeConfig | None = None) -> mock.MagicMock:
return manager
+def _page(key: str, rows: list[dict[str, Any]], next_cursor: str | None = None) -> ScriptedResponse:
+ return ScriptedResponse(json={key: rows, "meta": {"nextCursor": next_cursor} if next_cursor else {}})
+
+
+_Pages = dict[tuple[str, str | None, str | None], ScriptedResponse]
+
+
+def _vendor(pages: _Pages) -> Callable[[RecordedRequest], ScriptedResponse]:
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ parent_id = request.param("workspaceId") or request.param("taskId")
+ return pages[(request.path, parent_id, request.param("cursor"))]
+
+ return respond
+
+
+_WORKSPACE_PAGES: _Pages = {
+ ("/v1/workspaces", None, None): _page("workspaces", [{"id": "ws-1"}], next_cursor="ws-page-2"),
+ ("/v1/workspaces", None, "ws-page-2"): _page("workspaces", [{"id": "ws-2"}]),
+}
+
+_RECURRING_TASK_PAGES: _Pages = {
+ **_WORKSPACE_PAGES,
+ ("/v1/recurring-tasks", "ws-1", None): _page("tasks", [{"id": "rt-1"}], next_cursor="rt-page-2"),
+ ("/v1/recurring-tasks", "ws-1", "rt-page-2"): _page("tasks", [{"id": "rt-2"}]),
+ ("/v1/recurring-tasks", "ws-2", None): _page("tasks", [{"id": "rt-3"}]),
+}
+
+
class TestMotionSource:
def test_a_saved_cursor_seeds_the_paginator(self) -> None:
result = SourceDriver(MotionSource(), MotionSourceConfig(api_key="key")).run(
@@ -54,14 +84,128 @@ class TestMotionSource:
expected_clears: int,
) -> None:
manager = _manager()
- with mock.patch(f"{_MODULE}.rest_api_resource") as rest_api_resource:
+ resource = mock.MagicMock()
+ resource.name = "tasks"
+ with mock.patch(f"{_MODULE}.rest_api_resources", return_value=[resource]) as rest_api_resources:
motion_source("key", "tasks", 1, "job", manager)
- rest_api_resource.call_args.kwargs["resume_hook"](state)
+ rest_api_resources.call_args.kwargs["resume_hook"](state)
assert manager.save_state.call_args_list == expected_saves
assert manager.clear_state.call_count == expected_clears
+class TestMotionFanout:
+ @pytest.mark.parametrize(
+ "endpoint,pages,expected_rows",
+ [
+ (
+ "recurring_tasks",
+ _RECURRING_TASK_PAGES,
+ [
+ {"id": "rt-1", "workspaceId": "ws-1"},
+ {"id": "rt-2", "workspaceId": "ws-1"},
+ {"id": "rt-3", "workspaceId": "ws-2"},
+ ],
+ ),
+ (
+ "custom_fields",
+ {
+ **_WORKSPACE_PAGES,
+ ("/beta/workspaces/ws-1/custom-fields", None, None): ScriptedResponse(
+ json=[{"id": "cf-1", "field": "text"}, {"id": "cf-2", "field": "select"}]
+ ),
+ ("/beta/workspaces/ws-2/custom-fields", None, None): ScriptedResponse(json=[]),
+ },
+ [
+ {"id": "cf-1", "field": "text", "workspaceId": "ws-1"},
+ {"id": "cf-2", "field": "select", "workspaceId": "ws-1"},
+ ],
+ ),
+ (
+ "comments",
+ {
+ ("/v1/tasks", None, None): _page("tasks", [{"id": "t-1"}, {"id": "t-2"}, {"id": "t-3"}]),
+ ("/v1/comments", "t-1", None): _page(
+ "comments", [{"id": "c-1", "taskId": "t-1"}], next_cursor="c-page-2"
+ ),
+ ("/v1/comments", "t-1", "c-page-2"): _page("comments", [{"id": "c-2", "taskId": "t-1"}]),
+ # The task was deleted after the task list was read.
+ ("/v1/comments", "t-2", None): ScriptedResponse(status=404, json={"message": "Not found"}),
+ ("/v1/comments", "t-3", None): _page("comments", [{"id": "c-1", "taskId": "t-3"}]),
+ },
+ [
+ {"id": "c-1", "taskId": "t-1"},
+ {"id": "c-2", "taskId": "t-1"},
+ {"id": "c-1", "taskId": "t-3"},
+ ],
+ ),
+ ],
+ )
+ def test_walks_every_parent_and_child_page(
+ self,
+ endpoint: str,
+ pages: _Pages,
+ expected_rows: list[dict[str, Any]],
+ ) -> None:
+ result = SourceDriver(MotionSource(), MotionSourceConfig(api_key="key")).run(endpoint, _vendor(pages))
+
+ assert result.raised is None
+ assert result.rows == expected_rows
+ assert len(result.requests) == len(pages)
+ assert result.saved_states
+ assert all(state.fanout_state is not None for state in result.saved_states)
+ # Fan-out progress must not outlive a finished run, or the next sync would skip every parent.
+ assert result.completed_state is None
+
+ def test_comments_cover_tasks_in_every_status(self) -> None:
+ pages: _Pages = {
+ ("/v1/tasks", None, None): _page("tasks", [{"id": "t-1"}]),
+ ("/v1/comments", "t-1", None): _page("comments", []),
+ }
+
+ result = SourceDriver(MotionSource(), MotionSourceConfig(api_key="key")).run("comments", _vendor(pages))
+
+ assert result.raised is None
+ assert [request.param("includeAllStatuses") for request in result.requests if request.path == "/v1/tasks"] == [
+ "true"
+ ]
+
+ @pytest.mark.parametrize(
+ "fanout_state,expected_child_requests",
+ [
+ (
+ {"completed": ["/v1/recurring-tasks?workspaceId=ws-1"], "current": None, "child_state": None},
+ [("ws-2", None)],
+ ),
+ (
+ {
+ "completed": [],
+ "current": "/v1/recurring-tasks?workspaceId=ws-1",
+ "child_state": {"cursor": "rt-page-2"},
+ },
+ [("ws-1", "rt-page-2"), ("ws-2", None)],
+ ),
+ ],
+ )
+ def test_a_saved_fanout_state_skips_finished_parents(
+ self,
+ fanout_state: dict[str, Any],
+ expected_child_requests: list[tuple[str, str | None]],
+ ) -> None:
+ result = SourceDriver(MotionSource(), MotionSourceConfig(api_key="key")).run(
+ "recurring_tasks",
+ _vendor(_RECURRING_TASK_PAGES),
+ resume_state=MotionResumeConfig(fanout_state=fanout_state),
+ )
+
+ assert result.raised is None
+ assert [
+ (request.param("workspaceId"), request.param("cursor"))
+ for request in result.requests
+ if request.path == "/v1/recurring-tasks"
+ ] == expected_child_requests
+
+
class TestMotionCredentials:
@pytest.mark.parametrize(
"status_code,expected_valid",