: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement todoist import source (#65639)
Tom Owers88e92ca29a5a
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 8adfc53769fb..ec6b0be069f9 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -195,6 +195,7 @@ the row lists both.| teamwork | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ || tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |+| todoist | HTTP | requests | ✅ || trello | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -662,7 +663,6 @@ doesn't conflict with concurrent PRs.- timely- tinyemail- tmdb-- todoist- toggl- track_pms- tremendousdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex e5b850c4d155..74f37a729b0f 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -3139,7 +3139,7 @@ class TinyemailSourceConfig(config.Config):@config.configclass TodoistSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/todoist/canonical_descriptions.py b/posthog/temporal/data_imports/sources/todoist/canonical_descriptions.pynew file mode 100644index 000000000000..96ad4bc60cde--- /dev/null+++ b/posthog/temporal/data_imports/sources/todoist/canonical_descriptions.py@@ -0,0 +1,75 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Sourced from the official Todoist unified v1 API documentation (https://developer.todoist.com/api/v1).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "tasks": {+ "description": "Active (non-completed) tasks in the user's Todoist account.",+ "docs_url": "https://developer.todoist.com/api/v1#tag/Tasks",+ "columns": {+ "id": "Unique identifier of the task.",+ "content": "The task's text content, supporting Markdown.",+ "description": "A longer description attached to the task.",+ "project_id": "ID of the project the task belongs to.",+ "section_id": "ID of the section the task belongs to, if any.",+ "parent_id": "ID of the parent task for sub-tasks, if any.",+ "priority": "Task priority from 1 (normal) to 4 (urgent).",+ "labels": "Names of the labels associated with the task.",+ "is_completed": "Whether the task has been completed.",+ "added_at": "Date and time the task was created.",+ "completed_at": "Date and time the task was completed, if it has been.",+ "updated_at": "Date and time the task was last updated.",+ "due": "Object describing the task's due date, if set.",+ "url": "URL to access the task in the Todoist web app.",+ },+ },+ "projects": {+ "description": "Projects (top-level task containers) in the user's Todoist account.",+ "docs_url": "https://developer.todoist.com/api/v1#tag/Projects",+ "columns": {+ "id": "Unique identifier of the project.",+ "name": "Name of the project.",+ "description": "Description of the project.",+ "color": "Color of the project icon.",+ "parent_id": "ID of the parent project for nested projects, if any.",+ "is_favorite": "Whether the project is marked as a favorite.",+ "is_inbox_project": "Whether the project is the user's Inbox.",+ "workspace_id": "ID of the workspace the project belongs to, if any.",+ "folder_id": "ID of the folder the project belongs to, if any.",+ "created_at": "Date and time the project was created.",+ "updated_at": "Date and time the project was last updated.",+ "url": "URL to access the project in the Todoist web app.",+ },+ },+ "sections": {+ "description": "Sections used to group tasks within a project.",+ "docs_url": "https://developer.todoist.com/api/v1#tag/Sections",+ "columns": {+ "id": "Unique identifier of the section.",+ "name": "Name of the section.",+ "project_id": "ID of the project the section belongs to.",+ "order": "Position of the section within the project.",+ },+ },+ "labels": {+ "description": "Personal labels that can be applied to tasks.",+ "docs_url": "https://developer.todoist.com/api/v1#tag/Labels",+ "columns": {+ "id": "Unique identifier of the label.",+ "name": "Name of the label.",+ "color": "Color of the label.",+ "order": "Position of the label in the label list.",+ "is_favorite": "Whether the label is marked as a favorite.",+ },+ },+ "collaborators": {+ "description": "Project<->collaborator membership: one row per (project, collaborator). The "+ "owning project_id is injected onto each collaborator row.",+ "docs_url": "https://developer.todoist.com/api/v1#tag/Projects",+ "columns": {+ "project_id": "ID of the project the collaborator has access to (injected by the connector).",+ "id": "Unique identifier of the collaborating user.",+ "name": "Full name of the collaborator.",+ "email": "Email address of the collaborator.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/todoist/settings.py b/posthog/temporal/data_imports/sources/todoist/settings.pynew file mode 100644index 000000000000..35fcb5f64d1e--- /dev/null+++ b/posthog/temporal/data_imports/sources/todoist/settings.py@@ -0,0 +1,66 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField++# Todoist's unified v1 REST API. The legacy REST v2 (/rest/v2) and Sync v8/v9 endpoints are+# being shut down in early 2026, so everything here targets /api/v1.+TODOIST_BASE_URL = "https://api.todoist.com/api/v1"+++@dataclass+class TodoistEndpointConfig:+ name: str+ path: str+ # Stable creation timestamp used to partition the Delta table. None when the resource exposes no+ # stable creation timestamp (e.g. labels, sections). Never use a mutable field like `updated_at`.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ # Fan out one paginated request per synced project, materializing the project<->collaborator+ # membership as rows. When True, `path` is a template with a `{project_id}` placeholder and the+ # synced project_id is injected onto every row.+ fan_out_over_projects: bool = False+++TODOIST_ENDPOINTS: dict[str, TodoistEndpointConfig] = {+ "tasks": TodoistEndpointConfig(+ name="tasks",+ path="/tasks",+ # Raw v1 task objects carry `added_at` as the creation timestamp (the official SDK aliases it+ # to `created_at`). Verified against the published SDK model, not a live token.+ partition_key="added_at",+ ),+ "projects": TodoistEndpointConfig(+ name="projects",+ path="/projects",+ partition_key="created_at",+ ),+ "sections": TodoistEndpointConfig(+ name="sections",+ path="/sections",+ ),+ "labels": TodoistEndpointConfig(+ name="labels",+ path="/labels",+ ),+ # Project<->collaborator membership is only reachable per project, so this fans out one request+ # per synced project. The collaborator id is unique per person but a person can belong to many+ # projects, so the primary key is composite to stay unique table-wide.+ "collaborators": TodoistEndpointConfig(+ name="collaborators",+ path="/projects/{project_id}/collaborators",+ primary_keys=["project_id", "id"],+ # One paginated request per project, so it's opt-in (off by default) to avoid the extra API+ # cost for users who don't need project<->collaborator membership.+ should_sync_default=False,+ fan_out_over_projects=True,+ ),+}++ENDPOINTS = tuple(TODOIST_ENDPOINTS.keys())++# The v1 REST endpoints expose no server-side timestamp filter (no `since`/`updated_after`), so every+# endpoint is full refresh — there is no genuine incremental field to advertise. Incremental sync on+# Todoist is only possible through the separate /sync delta API, which this source does not use yet.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in TODOIST_ENDPOINTS}diff --git a/posthog/temporal/data_imports/sources/todoist/source.py b/posthog/temporal/data_imports/sources/todoist/source.pyindex 84a65ddf4fbd..497f5b46a3b3 100644--- a/posthog/temporal/data_imports/sources/todoist/source.py+++ b/posthog/temporal/data_imports/sources/todoist/source.py@@ -1,20 +1,33 @@-from typing import cast+from typing import Optional, castfrom 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.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import TodoistSourceConfig+from posthog.temporal.data_imports.sources.todoist.settings import ENDPOINTS, INCREMENTAL_FIELDS, TODOIST_ENDPOINTS+from posthog.temporal.data_imports.sources.todoist.todoist import (+ TodoistResumeConfig,+ todoist_source,+ validate_credentials as validate_todoist_credentials,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class TodoistSource(SimpleSource[TodoistSourceConfig]):+class TodoistSource(ResumableSource[TodoistSourceConfig, TodoistResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TODOIST@@ -25,7 +38,89 @@ class TodoistSource(SimpleSource[TodoistSourceConfig]):name=SchemaExternalDataSourceType.TODOIST,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Todoist",- iconPath="/static/services/todoist.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Todoist API token to automatically pull your Todoist data into the PostHog Data warehouse.++You can find your personal API token in [Todoist's integration settings](https://app.todoist.com/app/settings/integrations/developer).""",+ iconPath="/static/services/todoist.png",+ docsUrl="https://posthog.com/docs/cdp/sources/todoist",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="0123456789abcdef...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.todoist.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad, revoked, or insufficiently-scoped token surfaces as a requests HTTPError when+ # `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential+ # problem, so stop the sync. Match the stable status text and base host, not the+ # per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.todoist.com": "Your Todoist API token is invalid or has been revoked. Generate a new token in your Todoist integration settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.todoist.com": "Your Todoist API token is missing the permissions needed to sync this data. Reconnect with a token that has the required access.",+ }++ def get_schemas(+ self,+ config: TodoistSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = TODOIST_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ # Todoist's v1 REST endpoints expose no server-side timestamp filter, so every+ # endpoint is full refresh — no genuine incremental/append mode to offer.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.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: TodoistSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_todoist_credentials(config.api_token):+ return True, None++ return False, "Invalid Todoist API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TodoistResumeConfig]:+ return ResumableSourceManager[TodoistResumeConfig](inputs, TodoistResumeConfig)++ def source_for_pipeline(+ self,+ config: TodoistSourceConfig,+ resumable_source_manager: ResumableSourceManager[TodoistResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return todoist_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/todoist/tests/test_todoist.py b/posthog/temporal/data_imports/sources/todoist/tests/test_todoist.pynew file mode 100644index 000000000000..8e1b265fbd26--- /dev/null+++ b/posthog/temporal/data_imports/sources/todoist/tests/test_todoist.py@@ -0,0 +1,326 @@+from typing import Any++from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.todoist import todoist+from posthog.temporal.data_imports.sources.todoist.settings import INCREMENTAL_FIELDS, TODOIST_ENDPOINTS+from posthog.temporal.data_imports.sources.todoist.todoist import (+ PAGE_LIMIT,+ TodoistResumeConfig,+ _build_url,+ _parse_page,+ get_rows,+ todoist_source,+)+++class _FakeResumableManager:+ def __init__(self, state: TodoistResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[TodoistResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> TodoistResumeConfig | None:+ return self._state++ def save_state(self, data: TodoistResumeConfig) -> None:+ self.saved.append(data)+++def _response_with_status(status_code: int) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ return response+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert _build_url("/tasks", {}) == "https://api.todoist.com/api/v1/tasks"++ def test_with_params_is_encoded(self) -> None:+ # Cursors can contain characters that must be percent-encoded.+ assert _build_url("/tasks", {"limit": 200, "cursor": "a b/c"}) == (+ "https://api.todoist.com/api/v1/tasks?limit=200&cursor=a+b%2Fc"+ )+++class TestParsePage:+ @parameterized.expand(+ [+ (+ "wrapped_shape_with_cursor",+ {"results": [{"id": "1"}, {"id": "2"}], "next_cursor": "abc"},+ [{"id": "1"}, {"id": "2"}],+ "abc",+ ),+ (+ "wrapped_shape_last_page",+ {"results": [{"id": "1"}], "next_cursor": None},+ [{"id": "1"}],+ None,+ ),+ ("bare_array_has_no_cursor", [{"id": "1"}, {"id": "2"}], [{"id": "1"}, {"id": "2"}], None),+ ("empty_wrapped", {"results": [], "next_cursor": None}, [], None),+ ]+ )+ def test_parse_page(self, _name: str, data: Any, expected_rows: list[dict], expected_cursor: str | None) -> None:+ rows, cursor = _parse_page(data)+ assert rows == expected_rows+ assert cursor == expected_cursor+++class TestEndpointConfig:+ def test_collaborators_is_fan_out_with_composite_key(self) -> None:+ config = TODOIST_ENDPOINTS["collaborators"]+ assert config.fan_out_over_projects is True+ # A collaborator can belong to many projects, so the key must include the parent project.+ assert config.primary_keys == ["project_id", "id"]+ assert config.partition_key is None+ # Fan-out adds an API request per project, so it's opt-in.+ assert config.should_sync_default is False++ @parameterized.expand(+ [+ ("tasks", "added_at"),+ ("projects", "created_at"),+ ("sections", None),+ ("labels", None),+ ]+ )+ def test_partition_keys_are_stable_creation_fields(self, endpoint: str, expected_partition: str | None) -> None:+ # Partition keys must be stable creation timestamps, never a mutable field like updated_at.+ config = TODOIST_ENDPOINTS[endpoint]+ assert config.partition_key == expected_partition+ assert config.partition_key != "updated_at"++ def test_no_endpoint_advertises_incremental_fields(self) -> None:+ # The v1 REST API has no server-side timestamp filter, so nothing advertises incremental fields.+ assert all(fields == [] for fields in INCREMENTAL_FIELDS.values())+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("tasks", ["id"], "datetime", "added_at"),+ ("projects", ["id"], "datetime", "created_at"),+ ("sections", ["id"], None, None),+ ("labels", ["id"], None, None),+ ("collaborators", ["project_id", "id"], None, None),+ ]+ )+ def test_source_response_shape(+ self,+ endpoint: str,+ expected_keys: list[str],+ expected_partition_mode: str | None,+ expected_partition_key: str | None,+ ) -> None:+ response = todoist_source(+ api_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ assert response.partition_mode == expected_partition_mode+ assert response.partition_keys == ([expected_partition_key] if expected_partition_key else None)+ # Ascending order is the safe default; we never declare desc here.+ assert response.sort_mode == "asc"+++def _collect(manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: dict[str, Any]) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(todoist, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for batch in get_rows(+ api_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestTopLevelPagination:+ def test_follows_next_cursor_across_pages(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.todoist.com/api/v1/tasks?limit={PAGE_LIMIT}": {+ "results": [{"id": "T1"}],+ "next_cursor": "c2",+ },+ f"https://api.todoist.com/api/v1/tasks?limit={PAGE_LIMIT}&cursor=c2": {+ "results": [{"id": "T2"}],+ "next_cursor": None,+ },+ }+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "tasks", pages)+ assert rows == [{"id": "T1"}, {"id": "T2"}]++ def test_saves_cursor_after_yielding_each_page(self, monkeypatch: Any) -> None:+ # State must be saved AFTER yielding so a crash re-yields the last page rather than skipping it.+ pages = {+ f"https://api.todoist.com/api/v1/tasks?limit={PAGE_LIMIT}": {+ "results": [{"id": "T1"}],+ "next_cursor": "c2",+ },+ f"https://api.todoist.com/api/v1/tasks?limit={PAGE_LIMIT}&cursor=c2": {+ "results": [{"id": "T2"}],+ "next_cursor": None,+ },+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, "tasks", pages)+ # Only one save: after the first page (which has a next cursor). The last page has none.+ assert [s.next_cursor for s in manager.saved] == ["c2"]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.todoist.com/api/v1/tasks?limit={PAGE_LIMIT}&cursor=saved": {+ "results": [{"id": "T9"}],+ "next_cursor": None,+ },+ }+ manager = _FakeResumableManager(TodoistResumeConfig(next_cursor="saved"))+ rows = _collect(manager, monkeypatch, "tasks", pages)+ # Resumes mid-pagination from the saved cursor instead of restarting at page one.+ assert rows == [{"id": "T9"}]++ def test_empty_first_page_terminates(self, monkeypatch: Any) -> None:+ pages: dict[str, Any] = {+ f"https://api.todoist.com/api/v1/labels?limit={PAGE_LIMIT}": {"results": [], "next_cursor": None},+ }+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "labels", pages)+ assert rows == []+ assert manager.saved == []+++class TestCollaboratorsFanOut:+ def test_injects_project_id_onto_every_row(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.todoist.com/api/v1/projects?limit={PAGE_LIMIT}": {+ "results": [{"id": "P1"}, {"id": "P2"}],+ "next_cursor": None,+ },+ f"https://api.todoist.com/api/v1/projects/P1/collaborators?limit={PAGE_LIMIT}": {+ "results": [{"id": "U1", "name": "Ann"}, {"id": "U2", "name": "Bob"}],+ "next_cursor": None,+ },+ f"https://api.todoist.com/api/v1/projects/P2/collaborators?limit={PAGE_LIMIT}": {+ "results": [{"id": "U1", "name": "Ann"}],+ "next_cursor": None,+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, "collaborators", pages)+ assert rows == [+ {"id": "U1", "name": "Ann", "project_id": "P1"},+ {"id": "U2", "name": "Bob", "project_id": "P1"},+ {"id": "U1", "name": "Ann", "project_id": "P2"},+ ]++ def test_follows_collaborator_pagination(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.todoist.com/api/v1/projects?limit={PAGE_LIMIT}": {+ "results": [{"id": "P1"}],+ "next_cursor": None,+ },+ f"https://api.todoist.com/api/v1/projects/P1/collaborators?limit={PAGE_LIMIT}": {+ "results": [{"id": "U1"}],+ "next_cursor": "next",+ },+ f"https://api.todoist.com/api/v1/projects/P1/collaborators?limit={PAGE_LIMIT}&cursor=next": {+ "results": [{"id": "U2"}],+ "next_cursor": None,+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, "collaborators", pages)+ assert rows == [+ {"id": "U1", "project_id": "P1"},+ {"id": "U2", "project_id": "P1"},+ ]++ def test_project_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:+ not_found = requests.HTTPError(response=_response_with_status(404))+ pages = {+ f"https://api.todoist.com/api/v1/projects?limit={PAGE_LIMIT}": {+ "results": [{"id": "P1"}, {"id": "GONE"}, {"id": "P2"}],+ "next_cursor": None,+ },+ f"https://api.todoist.com/api/v1/projects/P1/collaborators?limit={PAGE_LIMIT}": {+ "results": [{"id": "U1"}],+ "next_cursor": None,+ },+ f"https://api.todoist.com/api/v1/projects/GONE/collaborators?limit={PAGE_LIMIT}": not_found,+ f"https://api.todoist.com/api/v1/projects/P2/collaborators?limit={PAGE_LIMIT}": {+ "results": [{"id": "U2"}],+ "next_cursor": None,+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, "collaborators", pages)+ assert rows == [+ {"id": "U1", "project_id": "P1"},+ {"id": "U2", "project_id": "P2"},+ ]++ def test_resume_from_deleted_project_restarts_from_first(self, monkeypatch: Any) -> None:+ pages = {+ f"https://api.todoist.com/api/v1/projects?limit={PAGE_LIMIT}": {+ "results": [{"id": "P1"}],+ "next_cursor": None,+ },+ f"https://api.todoist.com/api/v1/projects/P1/collaborators?limit={PAGE_LIMIT}": {+ "results": [{"id": "U1"}],+ "next_cursor": None,+ },+ }+ manager = _FakeResumableManager(TodoistResumeConfig(next_cursor=None, project_id="DELETED"))+ rows = _collect(manager, monkeypatch, "collaborators", pages)+ assert rows == [{"id": "U1", "project_id": "P1"}]+++class TestFetchPageRetryClassification:+ # Call the undecorated function so we assert classification without tenacity's backoff sleeps.+ _fetch = staticmethod(todoist._fetch_page.__wrapped__) # type: ignore[attr-defined]++ @parameterized.expand([(429,), (500,), (503,)])+ def test_retryable_statuses_raise_retryable_error(self, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _response_with_status(status_code)+ try:+ self._fetch(session, "https://api.todoist.com/api/v1/tasks", {}, MagicMock())+ except todoist.TodoistRetryableError:+ return+ raise AssertionError("expected TodoistRetryableError to be raised")++ @parameterized.expand([(401,), (403,), (404,)])+ def test_client_errors_raise_http_error(self, status_code: int) -> None:+ # 4xx (other than 429) are permanent — raise_for_status, not a retryable error.+ session = MagicMock()+ session.get.return_value = _response_with_status(status_code)+ try:+ self._fetch(session, "https://api.todoist.com/api/v1/tasks", {}, MagicMock())+ except todoist.TodoistRetryableError as exc:+ raise AssertionError("client errors must not be classified retryable") from exc+ except requests.HTTPError:+ return+ raise AssertionError("expected HTTPError to be raised")++ def test_success_returns_json_body(self) -> None:+ session = MagicMock()+ body: dict[str, Any] = {"results": [], "next_cursor": None}+ session.get.return_value = MagicMock(status_code=200, ok=True, **{"json.return_value": body})+ assert self._fetch(session, "https://api.todoist.com/api/v1/tasks", {}, MagicMock()) == bodydiff --git a/posthog/temporal/data_imports/sources/todoist/tests/test_todoist_source.py b/posthog/temporal/data_imports/sources/todoist/tests/test_todoist_source.pynew file mode 100644index 000000000000..56ac42ece103--- /dev/null+++ b/posthog/temporal/data_imports/sources/todoist/tests/test_todoist_source.py@@ -0,0 +1,125 @@+from typing import Any++from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import TodoistSourceConfig+from posthog.temporal.data_imports.sources.todoist import source as source_module+from posthog.temporal.data_imports.sources.todoist.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.todoist.source import TodoistSource+from posthog.temporal.data_imports.sources.todoist.todoist import TodoistResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = overrides.get("schema_name", "tasks")+ return inputs+++class TestTodoistSource:+ def setup_method(self) -> None:+ self.source = TodoistSource()+ self.team_id = 123+ self.config = TodoistSourceConfig(api_token="tok-test")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TODOIST++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Todoist"+ assert config.label == "Todoist"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Stays hidden until the source is promoted out of alpha.+ assert config.unreleasedSource is True+ assert len(config.fields) == 1++ token_field = config.fields[0]+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.name == "api_token"+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ # The token is sent to the API, so it must be stored as a secret.+ assert token_field.secret is True++ def test_get_schemas_matches_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_are_all_full_refresh(self) -> None:+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tasks", "projects"])+ assert {s.name for s in schemas} == {"tasks", "projects"}++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # Each declared endpoint should ship a curated description so it isn't sent to the LLM.+ described = set(self.source.get_canonical_descriptions().keys())+ assert set(ENDPOINTS).issubset(described)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.todoist.com/api/v1/tasks?limit=200",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.todoist.com/api/v1/projects",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.todoist.com', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.todoist.com/api/v1/tasks"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.todoist.com/api/v1/tasks"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_validate_credentials_success(self) -> None:+ with mock.patch.object(source_module, "validate_todoist_credentials", return_value=True) as probe:+ ok, error = self.source.validate_credentials(self.config, self.team_id)+ assert ok is True+ assert error is None+ probe.assert_called_once_with("tok-test")++ def test_validate_credentials_failure(self) -> None:+ with mock.patch.object(source_module, "validate_todoist_credentials", return_value=False):+ ok, error = self.source.validate_credentials(self.config, self.team_id)+ assert ok is False+ assert error == "Invalid Todoist API token"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TodoistResumeConfig++ def test_source_for_pipeline_plumbs_token_and_endpoint(self) -> None:+ manager = mock.MagicMock()+ inputs = _make_inputs(schema_name="projects")+ with mock.patch.object(source_module, "todoist_source") as todoist_source_fn:+ self.source.source_for_pipeline(self.config, manager, inputs)+ todoist_source_fn.assert_called_once_with(+ api_token="tok-test",+ endpoint="projects",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )diff --git a/posthog/temporal/data_imports/sources/todoist/todoist.py b/posthog/temporal/data_imports/sources/todoist/todoist.pynew file mode 100644index 000000000000..a67f5b948ead--- /dev/null+++ b/posthog/temporal/data_imports/sources/todoist/todoist.py@@ -0,0 +1,243 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.todoist.settings import (+ TODOIST_BASE_URL,+ TODOIST_ENDPOINTS,+ TodoistEndpointConfig,+)++# Todoist caps list endpoints at 200 items per page. Verified against the published API docs, not a+# live token — the paginator follows `next_cursor` regardless, so an over-large value would only ever+# cost an extra round trip if the cap turns out lower.+PAGE_LIMIT = 200++# Bound retries deterministically (5 attempts) so a wedged endpoint fails cleanly instead of spinning.+MAX_RETRIES = 5+++class TodoistRetryableError(Exception):+ pass+++class TodoistResumeConfig:+ # Body cursor for the next page. None means "start at the first page".+ next_cursor: str | None = None+ # The project currently being processed during the collaborators fan-out. A stable project-ID+ # bookmark (not a positional index) so projects added/removed between a crash and the retry can't+ # resume us into the wrong project. None for the standard (non-fan-out) endpoints.+ project_id: str | None = None+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any]) -> str:+ base = f"{TODOIST_BASE_URL}{path}"+ if not params:+ return base+ return f"{base}?{urlencode(params)}"+++def validate_credentials(api_token: str) -> bool:+ # Cheapest authenticated probe: pull a single project. A genuine token returns 200; a bad/revoked+ # one returns 401. Network/DNS/timeout failures are intentionally not caught here so they+ # propagate rather than being misreported to the user as an invalid credential.+ url = _build_url("/projects", {"limit": 1})+ response = make_tracked_session().get(url, headers=_get_headers(api_token), timeout=10)+ return response.status_code == 200+++@retry(+ retry=retry_if_exception_type((TodoistRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict | list:+ response = session.get(url, headers=headers, timeout=60)++ # 429 (rate limit) and 5xx are transient — let tenacity back off and retry.+ if response.status_code == 429 or response.status_code >= 500:+ raise TodoistRetryableError(f"Todoist API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Todoist API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _parse_page(data: dict | list) -> tuple[list[dict], str | None]:+ """Normalize a Todoist v1 list response into (rows, next_cursor).++ The unified v1 API wraps lists as ``{"results": [...], "next_cursor": "..."}``. Some endpoints+ historically returned a bare array; handle both so the source is robust to either shape.+ """+ if isinstance(data, list):+ return data, None+ results = data.get("results", [])+ return results, data.get("next_cursor")+++def _iter_project_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ """Page through /projects and yield each project's id, following the body cursor."""+ url = _build_url("/projects", {"limit": PAGE_LIMIT})+ while True:+ data = _fetch_page(session, url, headers, logger)+ rows, next_cursor = _parse_page(data)+ for item in rows:+ yield item["id"]++ if not next_cursor:+ break+ url = _build_url("/projects", {"limit": PAGE_LIMIT, "cursor": next_cursor})+++def _get_collaborator_rows(+ config: TodoistEndpointConfig,+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TodoistResumeConfig],+) -> Iterator[list[dict]]:+ """Fan out over every project, materializing project<->collaborator membership.++ Each collaborator row gets the owning ``project_id`` injected so the composite primary key+ ``[project_id, id]`` stays unique table-wide. Full refresh only — there is no server-side+ incremental filter — so re-pulled rows on resume are deduped by the primary key on merge.+ """+ project_ids = list(_iter_project_ids(session, headers, logger))++ # Resolve the saved project-ID bookmark to the slice of projects still to process. If the+ # bookmarked project no longer exists (deleted between runs), start over from the first project —+ # merge dedupes the re-pulled rows on the primary key. `resume_cursor` is consumed by the first+ # project only.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = project_ids+ resume_cursor: str | None = None+ if resume is not None and resume.project_id is not None and resume.project_id in project_ids:+ remaining = project_ids[project_ids.index(resume.project_id) :]+ resume_cursor = resume.next_cursor+ logger.debug(f"Todoist: resuming collaborators from project_id={resume.project_id}, cursor={resume_cursor}")++ for index, project_id in enumerate(remaining):+ path = config.path.replace("{project_id}", project_id)+ cursor = resume_cursor+ resume_cursor = None # only the resumed-into project uses the saved cursor; the rest start fresh++ try:+ while True:+ params: dict[str, Any] = {"limit": PAGE_LIMIT}+ if cursor:+ params["cursor"] = cursor+ data = _fetch_page(session, _build_url(path, params), headers, logger)+ rows, next_cursor = _parse_page(data)++ if rows:+ yield [{**row, "project_id": project_id} for row in rows]+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the+ # last page rather than skipping it — merge dedupes on the primary key.+ if next_cursor:+ resumable_source_manager.save_state(+ TodoistResumeConfig(next_cursor=next_cursor, project_id=project_id)+ )++ if not next_cursor:+ break+ cursor = next_cursor+ except requests.HTTPError as exc:+ # A project deleted between enumeration and this fetch 404s. Skip it rather than failing+ # the whole sync — the membership is genuinely gone. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Todoist: project {project_id} not found while fetching collaborators, skipping")+ else:+ raise++ # Advance the bookmark to the next project so a crash between projects resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(TodoistResumeConfig(next_cursor=None, project_id=remaining[index + 1]))+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TodoistResumeConfig],+) -> Iterator[list[dict]]:+ config = TODOIST_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ # One session reused across every page (and, for fan-out, every project) so urllib3 keeps the+ # connection alive instead of re-handshaking per request.+ session = make_tracked_session()++ if config.fan_out_over_projects:+ yield from _get_collaborator_rows(config, session, headers, logger, resumable_source_manager)+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.next_cursor if resume is not None else None+ if cursor:+ logger.debug(f"Todoist: resuming {endpoint} from cursor={cursor}")++ while True:+ params: dict[str, Any] = {"limit": PAGE_LIMIT}+ if cursor:+ params["cursor"] = cursor+ data = _fetch_page(session, _build_url(config.path, params), headers, logger)+ rows, next_cursor = _parse_page(data)++ if rows:+ yield rows+ if next_cursor:+ resumable_source_manager.save_state(TodoistResumeConfig(next_cursor=next_cursor))++ if not next_cursor:+ break+ cursor = next_cursor+++def todoist_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TodoistResumeConfig],+) -> SourceResponse:+ endpoint_config = TODOIST_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ 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,+ )+++__all__ = ["TodoistResumeConfig", "get_rows", "todoist_source", "validate_credentials"]