: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 trello import source (#61658)
Tom Owers3c745fb7f8b5
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex c45604752afd..f6552478df97 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -130,6 +130,7 @@ the row lists both.| surveymonkey | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ || tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |+| trello | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -219,7 +220,6 @@ doesn't conflict with concurrent PRs.- sftp- sharepoint- surveymonkey-- trello- twitter_ads- workday- xerodiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex fe68e2b07ad3..688d540b8232 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -881,7 +881,8 @@ class TikTokAdsSourceConfig(config.Config):@config.configclass TrelloSourceConfig(config.Config):- pass+ api_key: str+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/trello/api_inventory.md b/posthog/temporal/data_imports/sources/trello/api_inventory.mdnew file mode 100644index 000000000000..8c53e8f76c85--- /dev/null+++ b/posthog/temporal/data_imports/sources/trello/api_inventory.md@@ -0,0 +1,48 @@+# Trello API inventory++Base URL: `https://api.trello.com/1`++Auth: API key + user token. Sent via the `Authorization` header+(`OAuth oauth_consumer_key="<key>", oauth_token="<token>"`) rather than the `?key=&token=`+query params, so the secret token never lands in request URLs (and therefore not in our+tracked-session request logs).++## Endpoints++| Schema | Path | Scope | Pagination | Incremental | Notes |+| --------------- | --------------------------- | ------ | ----------------------- | --------------- | ----------------------------------------------------- |+| `boards` | `/members/me/boards` | member | none (single request) | full | |+| `organizations` | `/members/me/organizations` | member | none (single request) | full | Trello workspaces |+| `lists` | `/boards/{id}/lists` | board | none (single request) | full | fan-out per board |+| `cards` | `/boards/{id}/cards` | board | none (single request) | full | fan-out per board; open cards only by default |+| `checklists` | `/boards/{id}/checklists` | board | none (single request) | full | fan-out per board |+| `labels` | `/boards/{id}/labels` | board | none (single request) | full | fan-out per board |+| `members` | `/boards/{id}/members` | board | none (single request) | full | board members; deduped across boards on `id` |+| `actions` | `/boards/{id}/actions` | board | `before`/`since` cursor | **incremental** | newest-first; `since` is a genuine server-side filter |++`boards` is fetched (id-only) before every board-scoped endpoint to drive the fan-out.++## Partitioning++Trello objects generally expose no creation timestamp, but their IDs are MongoDB ObjectIDs+whose first 8 hex chars encode the Unix creation time. We synthesise a stable `created_at`+field from the id on every row and partition on it (datetime / weekly).++## Incremental sync++Only `actions` exposes a server-side timestamp filter (`since`), so it's the only endpoint+shipped as incremental (cursor field `date`). Everything else is full refresh — matching the+Airbyte Trello connector, where only Actions supports incremental. Actions come back+descending by `date`, so the source reports `sort_mode="desc"` and pages backwards with the+`before` cursor while bounding the lower edge with `since`.++## Verification status++- `Authorization` header auth confirmed against the live API (bogus key → `401 invalid key`,+ no auth → `400 invalid token`).+- The `actions` `since` server-side filter and the exact pagination behaviour beyond 1000+ results were **not** verified against the live API (no test credentials available). The+ implementation follows the documented behaviour; if `since` turns out to be ignored on a+ given account, the sync still converges correctly because every fetched row is merged on its+ primary key. The known same-second pagination caveat (multiple objects created in the same+ second) is tolerated the same way.diff --git a/posthog/temporal/data_imports/sources/trello/settings.py b/posthog/temporal/data_imports/sources/trello/settings.pynew file mode 100644index 000000000000..6f1e601b7d2d--- /dev/null+++ b/posthog/temporal/data_imports/sources/trello/settings.py@@ -0,0 +1,96 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class TrelloEndpointConfig:+ name: str+ # For ``member`` scope this is the full path under the base URL+ # (e.g. ``/members/me/boards``). For ``board`` scope it is the trailing+ # segment fetched per board (e.g. ``cards`` → ``/boards/{board_id}/cards``).+ path: str+ # ``member`` = single top-level list request; ``board`` = fan out across the+ # authenticated member's boards and query the resource per board.+ scope: Literal["member", "board"]+ primary_key: str = "id"+ # We synthesise ``created_at`` from each object's ObjectID, so every endpoint+ # can partition on a stable creation timestamp (see ``_id_to_created_at``).+ partition_key: Optional[str] = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Trello caps a single response at 1000 objects. Only ``actions`` exposes the+ # ``before``/``since`` cursors needed to page past that and filter server-side.+ page_size: int = 1000+ paginated: bool = False+ sort_mode: Literal["asc", "desc"] = "asc"+++# Actions are the only Trello resource with a genuine server-side timestamp filter+# (``since``), so it's the only endpoint that supports incremental sync. Everything+# else is full refresh. ``date`` is the action's immutable creation time.+_ACTIONS_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++TRELLO_ENDPOINTS: dict[str, TrelloEndpointConfig] = {+ "boards": TrelloEndpointConfig(+ name="boards",+ path="/members/me/boards",+ scope="member",+ ),+ "organizations": TrelloEndpointConfig(+ name="organizations",+ path="/members/me/organizations",+ scope="member",+ ),+ "lists": TrelloEndpointConfig(+ name="lists",+ path="lists",+ scope="board",+ ),+ "cards": TrelloEndpointConfig(+ name="cards",+ path="cards",+ scope="board",+ ),+ "checklists": TrelloEndpointConfig(+ name="checklists",+ path="checklists",+ scope="board",+ ),+ "labels": TrelloEndpointConfig(+ name="labels",+ path="labels",+ scope="board",+ ),+ "members": TrelloEndpointConfig(+ name="members",+ path="members",+ scope="board",+ ),+ "actions": TrelloEndpointConfig(+ name="actions",+ path="actions",+ scope="board",+ paginated=True,+ # Trello returns actions newest-first and ignores requests to sort+ # ascending, so the cursor watermark must be tracked as a descending feed.+ sort_mode="desc",+ incremental_fields=_ACTIONS_INCREMENTAL_FIELDS,+ default_incremental_field="date",+ ),+}++ENDPOINTS = tuple(TRELLO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TRELLO_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/trello/source.py b/posthog/temporal/data_imports/sources/trello/source.pyindex b52d0a7714d9..6ff7c0af9d80 100644--- a/posthog/temporal/data_imports/sources/trello/source.py+++ b/posthog/temporal/data_imports/sources/trello/source.py@@ -1,19 +1,31 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom 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 TrelloSourceConfig+from posthog.temporal.data_imports.sources.trello.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.trello.trello import (+ TrelloResumeConfig,+ trello_source,+ validate_credentials as validate_trello_credentials,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class TrelloSource(SimpleSource[TrelloSourceConfig]):+class TrelloSource(ResumableSource[TrelloSourceConfig, TrelloResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TRELLO@@ -23,7 +35,87 @@ class TrelloSource(SimpleSource[TrelloSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.TRELLO,label="Trello",- iconPath="/static/services/trello.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Trello API key and token to sync your boards, cards, lists and more into the PostHog Data warehouse.++Get your API key from [trello.com/power-ups/admin](https://trello.com/power-ups/admin) and generate a token with **read** access for your account.""",+ iconPath="/static/services/trello.png",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Trello API key",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Trello API token",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Trello API key or token. Please check your credentials and reconnect.",+ "403 Client Error": "Your Trello token does not have the required permissions. Please grant read access and reconnect.",+ "invalid key": "Invalid Trello API key. Please check your credentials and reconnect.",+ "invalid token": "Invalid or expired Trello token. Please generate a new token and reconnect.",+ }++ def get_schemas(+ self,+ config: TrelloSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: TrelloSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_trello_credentials(config.api_key, config.api_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TrelloResumeConfig]:+ return ResumableSourceManager[TrelloResumeConfig](inputs, TrelloResumeConfig)++ def source_for_pipeline(+ self,+ config: TrelloSourceConfig,+ resumable_source_manager: ResumableSourceManager[TrelloResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return trello_source(+ api_key=config.api_key,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/trello/tests/test_trello.py b/posthog/temporal/data_imports/sources/trello/tests/test_trello.pynew file mode 100644index 000000000000..5c26cc1bcf61--- /dev/null+++ b/posthog/temporal/data_imports/sources/trello/tests/test_trello.py@@ -0,0 +1,381 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, cast++from unittest import mock++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from posthog.temporal.data_imports.sources.trello.settings import TRELLO_ENDPOINTS+from posthog.temporal.data_imports.sources.trello.trello import (+ TrelloResumeConfig,+ _add_created_at,+ _format_incremental_value,+ _get_headers,+ _id_to_created_at,+ get_rows,+ trello_source,+ validate_credentials,+)+++def _make_response(status: int = 200, body: Any = None) -> mock.Mock:+ resp = mock.Mock()+ resp.status_code = status+ resp.ok = 200 <= status < 300+ resp.json.return_value = body if body is not None else []+ resp.text = ""+ return resp+++def _make_manager(*, can_resume: bool = False, resume_state: TrelloResumeConfig | None = None) -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = resume_state+ manager.save_state = mock.Mock()+ return manager+++class _ImmediateBatcher:+ """Test double for Batcher that emits every batched item as its own chunk."""++ def __init__(self) -> None:+ self._item: Any = None++ def batch(self, item: Any) -> None:+ self._item = item++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return self._item is not None++ def get_table(self) -> Any:+ item = self._item+ self._item = None+ return item+++def _patch_batcher() -> Any:+ return mock.patch(+ "posthog.temporal.data_imports.sources.trello.trello.Batcher",+ autospec=False,+ side_effect=lambda logger, chunk_size, chunk_size_bytes: _ImmediateBatcher(),+ )+++def _run(endpoint: str, manager: mock.Mock, get_mock: mock.Mock, **kwargs: Any) -> list[Any]:+ return list(+ get_rows(+ api_key="key",+ api_token="token",+ endpoint=endpoint,+ logger=mock.Mock(),+ resumable_source_manager=manager,+ **kwargs,+ )+ )+++class TestIdToCreatedAt:+ @parameterized.expand(+ [+ # 0x5abbe394 = 1522242964 = 2018-03-28T18:48:52+00:00+ ("valid_object_id", "5abbe394c78f17ffa9e10843", "2018-03-28T18:48:52+00:00"),+ ("too_short", "abc", None),+ ("non_hex_prefix", "zzzzzzzzc78f17ffa9e10843", None),+ ("not_a_string", 12345, None),+ ("none", None, None),+ ]+ )+ def test_id_to_created_at(self, _name: str, obj_id: Any, expected: str | None) -> None:+ assert _id_to_created_at(obj_id) == expected+++class TestAddCreatedAt:+ def test_injects_created_at_from_id(self) -> None:+ item = _add_created_at({"id": "5abbe394c78f17ffa9e10843", "name": "Board"})+ assert item["created_at"] == "2018-03-28T18:48:52+00:00"++ def test_preserves_existing_created_at(self) -> None:+ item = _add_created_at({"id": "5abbe394c78f17ffa9e10843", "created_at": "already"})+ assert item["created_at"] == "already"++ def test_no_id_leaves_item_unchanged(self) -> None:+ item = _add_created_at({"name": "no id"})+ assert "created_at" not in item+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("aware_datetime", datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC), "2026-01-15T10:00:00+00:00"),+ ("naive_datetime", datetime(2026, 1, 15, 10, 0, 0), "2026-01-15T10:00:00+00:00"),+ ("date", date(2026, 1, 15), "2026-01-15T00:00:00+00:00"),+ ("string_passthrough", "2026-01-15T10:00:00Z", "2026-01-15T10:00:00Z"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_incremental_value(value) == expected+++class TestGetHeaders:+ def test_oauth_header_keeps_token_out_of_url(self) -> None:+ headers = _get_headers("my-key", "my-token")+ assert headers["Authorization"] == 'OAuth oauth_consumer_key="my-key", oauth_token="my-token"'+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("missing_token", 400, False, "Invalid Trello API key or token"),+ ("invalid_key", 401, False, "Invalid Trello API key or token"),+ ("forbidden", 403, False, "Your Trello token does not have the required permissions"),+ ]+ )+ def test_status_codes(self, _name: str, status: int, valid: bool, message: str | None) -> None:+ with mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session:+ session.return_value.get.return_value = mock.MagicMock(status_code=status)+ result_valid, result_message = validate_credentials("key", "token")++ assert result_valid is valid+ assert result_message == message++ def test_request_exception(self) -> None:+ with mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session:+ session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")+ valid, message = validate_credentials("key", "token")++ assert valid is False+ assert message is not None+ assert "boom" in message++ def test_sends_oauth_header(self) -> None:+ with mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session:+ session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("my-key", "my-token")++ headers = session.return_value.get.call_args.kwargs["headers"]+ assert headers["Authorization"] == 'OAuth oauth_consumer_key="my-key", oauth_token="my-token"'+++class TestMemberEndpoint:+ def test_boards_single_request_injects_created_at(self) -> None:+ manager = _make_manager()+ boards = [{"id": "5abbe394c78f17ffa9e10843", "name": "A"}, {"id": "5abbe395c78f17ffa9e10843", "name": "B"}]++ with (+ _patch_batcher(),+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [_make_response(body=boards)]+ rows = _run("boards", manager, session, should_use_incremental_field=False)++ assert [r["name"] for r in rows] == ["A", "B"]+ assert all("created_at" in r for r in rows)+ # Member endpoints are a single request; no resume checkpoints.+ manager.save_state.assert_not_called()+ url = session.return_value.get.call_args_list[0].args[0]+ assert url.startswith("https://api.trello.com/1/members/me/boards")++ def test_non_list_body_yields_nothing(self) -> None:+ manager = _make_manager()+ with (+ _patch_batcher(),+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [_make_response(body={"error": "nope"})]+ rows = _run("organizations", manager, session)++ assert rows == []+++class TestBoardFanOut:+ def test_lists_fan_out_across_boards(self) -> None:+ manager = _make_manager()+ board_ids = [{"id": "board1"}, {"id": "board2"}]+ lists_b1 = [{"id": "l1"}]+ lists_b2 = [{"id": "l2"}, {"id": "l3"}]++ with (+ _patch_batcher(),+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [+ _make_response(body=board_ids),+ _make_response(body=lists_b1),+ _make_response(body=lists_b2),+ ]+ rows = _run("lists", manager, session)++ assert [r["id"] for r in rows] == ["l1", "l2", "l3"]+ urls = [c.args[0] for c in session.return_value.get.call_args_list]+ assert "/members/me/boards?fields=id" in urls[0]+ assert "/boards/board1/lists" in urls[1]+ assert "/boards/board2/lists" in urls[2]+ # Each completed board advances the resume index.+ saved_indices = [c.args[0].board_index for c in manager.save_state.call_args_list]+ assert saved_indices[-1] == 2++ def test_resume_skips_completed_boards(self) -> None:+ manager = _make_manager(can_resume=True, resume_state=TrelloResumeConfig(board_index=1, before_cursor=None))+ board_ids = [{"id": "board1"}, {"id": "board2"}]++ with (+ _patch_batcher(),+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [+ _make_response(body=board_ids),+ _make_response(body=[{"id": "l2"}]),+ ]+ rows = _run("lists", manager, session)++ # Only board2 (index 1) is synced; board1 is skipped.+ assert [r["id"] for r in rows] == ["l2"]+ urls = [c.args[0] for c in session.return_value.get.call_args_list]+ assert not any("/boards/board1/" in u for u in urls)+ assert any("/boards/board2/lists" in u for u in urls)+++class TestActionsIncremental:+ def test_incremental_sends_since_and_limit(self) -> None:+ manager = _make_manager()+ cutoff = datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC)++ with (+ _patch_batcher(),+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [+ _make_response(body=[{"id": "b1"}]),+ _make_response(body=[{"id": "a1", "date": "2026-02-01T00:00:00Z"}]),+ ]+ _run(+ "actions",+ manager,+ session,+ should_use_incremental_field=True,+ db_incremental_field_last_value=cutoff,+ )++ actions_url = session.return_value.get.call_args_list[1].args[0]+ assert "since=2026-01-15T10" in actions_url+ assert "limit=1000" in actions_url++ def test_full_refresh_omits_since(self) -> None:+ manager = _make_manager()+ with (+ _patch_batcher(),+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [+ _make_response(body=[{"id": "b1"}]),+ _make_response(body=[{"id": "a1"}]),+ ]+ _run("actions", manager, session, should_use_incremental_field=False)++ actions_url = session.return_value.get.call_args_list[1].args[0]+ assert "since=" not in actions_url++ def test_paginates_with_before_cursor(self) -> None:+ # Drive pagination directly with a small page size so we don't need 1000 rows.+ manager = _make_manager()+ config = dataclasses.replace(TRELLO_ENDPOINTS["actions"], page_size=2)++ from posthog.temporal.data_imports.sources.trello.trello import _sync_board_actions++ with (+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [+ _make_response(body=[{"id": "a1"}, {"id": "a2"}]), # full page → keep paging+ _make_response(body=[{"id": "a3"}]), # short page → stop+ ]+ batcher = _ImmediateBatcher()+ rows = list(+ _sync_board_actions(+ board_id="b1",+ index=0,+ config=config,+ headers={},+ logger=mock.Mock(),+ batcher=cast(Batcher, batcher),+ manager=manager,+ since=None,+ before=None,+ )+ )++ assert [r["id"] for r in rows] == ["a1", "a2", "a3"]+ urls = [c.args[0] for c in session.return_value.get.call_args_list]+ assert "before=" not in urls[0]+ assert "before=a2" in urls[1]+ # Board fully drained → resume index advances past this board.+ assert manager.save_state.call_args_list[-1].args[0].board_index == 1++ def test_resume_uses_before_cursor(self) -> None:+ manager = _make_manager(can_resume=True, resume_state=TrelloResumeConfig(board_index=0, before_cursor="oldest"))+ with (+ _patch_batcher(),+ mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session,+ ):+ session.return_value.get.side_effect = [+ _make_response(body=[{"id": "b1"}]),+ _make_response(body=[{"id": "a1"}]),+ ]+ _run("actions", manager, session, should_use_incremental_field=False)++ actions_url = session.return_value.get.call_args_list[1].args[0]+ assert "before=oldest" in actions_url+++class TestTrelloSourceResponse:+ @parameterized.expand(+ [+ ("boards", "asc", "id"),+ ("actions", "desc", "id"),+ ("cards", "asc", "id"),+ ]+ )+ def test_source_response_shape(self, endpoint: str, sort_mode: str, primary_key: str) -> None:+ response = trello_source(+ api_key="key",+ api_token="token",+ endpoint=endpoint,+ logger=mock.Mock(),+ resumable_source_manager=_make_manager(),+ )+ assert response.name == endpoint+ assert response.sort_mode == sort_mode+ assert response.primary_keys == [primary_key]+ assert response.partition_keys == ["created_at"]+ assert response.partition_mode == "datetime"++ @parameterized.expand([(name,) for name in TRELLO_ENDPOINTS])+ def test_every_endpoint_builds_a_response(self, endpoint: str) -> None:+ response = trello_source(+ api_key="key",+ api_token="token",+ endpoint=endpoint,+ logger=mock.Mock(),+ resumable_source_manager=_make_manager(),+ )+ assert callable(response.items)+ assert response.primary_keys == [TRELLO_ENDPOINTS[endpoint].primary_key]+++class TestRetryClassification:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise(self, _name: str, status: int) -> None:+ from posthog.temporal.data_imports.sources.trello.trello import TrelloRetryableError, _fetch++ with mock.patch("posthog.temporal.data_imports.sources.trello.trello.make_tracked_session") as session:+ session.return_value.get.return_value = _make_response(status=status)+ # __wrapped__ skips tenacity so we assert the single-attempt classification.+ try:+ _fetch.__wrapped__("https://api.trello.com/1/members/me", {}, mock.Mock()) # type: ignore[attr-defined]+ except TrelloRetryableError:+ return+ raise AssertionError("expected TrelloRetryableError")diff --git a/posthog/temporal/data_imports/sources/trello/tests/test_trello_source.py b/posthog/temporal/data_imports/sources/trello/tests/test_trello_source.pynew file mode 100644index 000000000000..2dff76a68661--- /dev/null+++ b/posthog/temporal/data_imports/sources/trello/tests/test_trello_source.py@@ -0,0 +1,132 @@+from typing import Any++from unittest import mock++from parameterized import parameterized++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.trello.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.trello.source import TrelloSource+from posthog.temporal.data_imports.sources.trello.trello import TrelloResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _config() -> Any:+ return TrelloSource().parse_config({"api_key": "key", "api_token": "token"})+++def _inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "actions",+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": True,+ "db_incremental_field_last_value": "2026-01-01T00:00:00Z",+ "db_incremental_field_earliest_value": None,+ "incremental_field": "date",+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": mock.Mock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestSourceType:+ def test_source_type(self) -> None:+ assert TrelloSource().source_type == ExternalDataSourceType.TRELLO+++class TestSourceConfig:+ def test_config_fields(self) -> None:+ config = TrelloSource().get_source_config+ assert config.label == "Trello"+ assert config.unreleasedSource is True+ assert config.releaseStatus == "alpha"+ assert [f.name for f in config.fields] == ["api_key", "api_token"]+ # Both credentials must be stored as secrets.+ assert all(getattr(f, "secret", False) for f in config.fields)+++class TestGetSchemas:+ def test_only_actions_supports_incremental(self) -> None:+ schemas = {s.name: s for s in TrelloSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ assert schemas["actions"].supports_incremental is True+ assert [f["field"] for f in schemas["actions"].incremental_fields] == ["date"]+ for name in ("boards", "cards", "lists", "organizations", "checklists", "labels", "members"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_names_filter(self) -> None:+ schemas = TrelloSource().get_schemas(_config(), team_id=1, names=["cards", "actions"])+ assert {s.name for s in schemas} == {"cards", "actions"}+++class TestValidateCredentials:+ @parameterized.expand([("valid", (True, None)), ("invalid", (False, "Invalid Trello API key or token"))])+ def test_delegates_to_transport(self, _name: str, transport_result: tuple[bool, str | None]) -> None:+ with mock.patch(+ "posthog.temporal.data_imports.sources.trello.source.validate_trello_credentials",+ return_value=transport_result,+ ) as validate:+ result = TrelloSource().validate_credentials(_config(), team_id=1)++ assert result == transport_result+ validate.assert_called_once_with("key", "token")+++class TestGetNonRetryableErrors:+ def test_covers_auth_failures(self) -> None:+ errors = TrelloSource().get_non_retryable_errors()+ assert "401 Client Error" in errors+ assert "403 Client Error" in errors+ assert "invalid key" in errors+ assert "invalid token" in errors+++class TestResumableSourceManager:+ def test_manager_bound_to_resume_config(self) -> None:+ manager = TrelloSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TrelloResumeConfig+++class TestSourceForPipeline:+ @parameterized.expand(+ [+ ("incremental", "actions", True, "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"),+ # The cursor value is dropped when the schema is not synced incrementally.+ ("full_refresh", "boards", False, "2026-01-01T00:00:00Z", None),+ ]+ )+ def test_plumbs_arguments(+ self,+ _name: str,+ schema_name: str,+ incremental: bool,+ last_value: str,+ expected_last_value: str | None,+ ) -> None:+ manager = mock.Mock()+ with mock.patch("posthog.temporal.data_imports.sources.trello.source.trello_source") as trello_source:+ TrelloSource().source_for_pipeline(+ _config(),+ manager,+ _inputs(+ schema_name=schema_name,+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=last_value,+ ),+ )++ kwargs = trello_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["api_token"] == "token"+ assert kwargs["endpoint"] == schema_name+ assert kwargs["should_use_incremental_field"] is incremental+ assert kwargs["db_incremental_field_last_value"] == expected_last_valuediff --git a/posthog/temporal/data_imports/sources/trello/trello.py b/posthog/temporal/data_imports/sources/trello/trello.pynew file mode 100644index 000000000000..2b80ce2e9718--- /dev/null+++ b/posthog/temporal/data_imports/sources/trello/trello.py@@ -0,0 +1,315 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.trello.settings import TRELLO_ENDPOINTS, TrelloEndpointConfig++TRELLO_BASE_URL = "https://api.trello.com/1"+++class TrelloRetryableError(Exception):+ pass+++class TrelloResumeConfig:+ # Number of boards fully synced; board-scoped endpoints resume past these.+ board_index: int = 0+ # Oldest action id of the last fetched page within the in-progress board+ # (actions only) — used as the ``before`` cursor to re-enter pagination.+ before_cursor: str | None = None+++def _get_headers(api_key: str, api_token: str) -> dict[str, str]:+ # Header auth keeps the secret token out of request URLs (and therefore out of+ # our tracked-session request logs), unlike Trello's ?key=&token= query params.+ return {"Authorization": f'OAuth oauth_consumer_key="{api_key}", oauth_token="{api_token}"'}+++def _id_to_created_at(obj_id: Any) -> str | None:+ """Derive a creation timestamp from a Trello ObjectID.++ Trello IDs are MongoDB ObjectIDs whose first 8 hex chars encode the Unix+ creation time. Most Trello objects expose no creation timestamp of their own,+ so we surface this as a stable ``created_at`` for partitioning.+ """+ if not isinstance(obj_id, str) or len(obj_id) < 8:+ return None+ try:+ timestamp = int(obj_id[:8], 16)+ except ValueError:+ return None+ return datetime.fromtimestamp(timestamp, tz=UTC).isoformat()+++def _add_created_at(item: dict[str, Any]) -> dict[str, Any]:+ if "created_at" not in item:+ created_at = _id_to_created_at(item.get("id"))+ if created_at is not None:+ item["created_at"] = created_at+ return item+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value as an ISO 8601 string for Trello's ``since`` filter."""+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ return utc_value.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++@retry(+ retry=retry_if_exception_type((TrelloRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch(url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> requests.Response:+ response = make_tracked_session().get(url, headers=headers, timeout=60)++ # Trello rate-limits aggressively (300 req/10s per key, 100 req/10s per token)+ # and returns 429 when exceeded; retry those plus transient 5xx with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise TrelloRetryableError(f"Trello API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Trello API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def validate_credentials(api_key: str, api_token: str) -> tuple[bool, str | None]:+ url = f"{TRELLO_BASE_URL}/members/me"+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key, api_token), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None++ # Trello answers a missing/invalid token with 400 ("invalid token") and an+ # invalid key with 401 ("invalid key"); both mean the credentials are bad.+ if response.status_code in (400, 401):+ return False, "Invalid Trello API key or token"+ if response.status_code == 403:+ return False, "Your Trello token does not have the required permissions"++ return False, response.text or f"Trello API returned status {response.status_code}"+++def _fetch_board_ids(headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:+ url = f"{TRELLO_BASE_URL}/members/me/boards?{urlencode({'fields': 'id'})}"+ data = _fetch(url, headers, logger).json()+ if not isinstance(data, list):+ return []+ return [board["id"] for board in data if isinstance(board, dict) and board.get("id")]+++def _sync_member_endpoint(+ config: TrelloEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+) -> Iterator[Any]:+ url = f"{TRELLO_BASE_URL}{config.path}?{urlencode({'limit': config.page_size})}"+ data = _fetch(url, headers, logger).json()+ if not isinstance(data, list):+ return++ if len(data) >= config.page_size:+ logger.warning(+ f"Trello {config.name} returned {len(data)} rows at the {config.page_size} page cap; "+ "results may be truncated."+ )++ for item in data:+ if not isinstance(item, dict):+ continue+ batcher.batch(_add_created_at(item))+ if batcher.should_yield():+ yield batcher.get_table()+++def _sync_board_simple(+ board_id: str,+ index: int,+ config: TrelloEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[TrelloResumeConfig],+) -> Iterator[Any]:+ url = f"{TRELLO_BASE_URL}/boards/{board_id}/{config.path}?{urlencode({'limit': config.page_size})}"+ data = _fetch(url, headers, logger).json()++ if isinstance(data, list):+ if len(data) >= config.page_size:+ logger.warning(+ f"Trello {config.name} for board {board_id} returned {len(data)} rows at the "+ f"{config.page_size} page cap; results may be truncated."+ )+ for item in data:+ if not isinstance(item, dict):+ continue+ batcher.batch(_add_created_at(item))+ if batcher.should_yield():+ yield batcher.get_table()+ manager.save_state(TrelloResumeConfig(board_index=index, before_cursor=None))++ # Board complete: the next resume starts at the following board.+ manager.save_state(TrelloResumeConfig(board_index=index + 1, before_cursor=None))+++def _sync_board_actions(+ board_id: str,+ index: int,+ config: TrelloEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[TrelloResumeConfig],+ since: str | None,+ before: str | None,+) -> Iterator[Any]:+ # Actions come back newest-first. We page backwards with ``before`` (the oldest+ # id of the previous page) and bound the lower edge with ``since`` for+ # incremental syncs. Both filters can be combined, so a single run only fetches+ # actions newer than the watermark.+ while True:+ params: dict[str, Any] = {"limit": config.page_size}+ if since:+ params["since"] = since+ if before:+ params["before"] = before++ url = f"{TRELLO_BASE_URL}/boards/{board_id}/actions?{urlencode(params)}"+ data = _fetch(url, headers, logger).json()+ if not isinstance(data, list) or not data:+ break++ oldest_id = data[-1]["id"] if isinstance(data[-1], dict) else None++ for item in data:+ if not isinstance(item, dict):+ continue+ batcher.batch(_add_created_at(item))+ if batcher.should_yield():+ yield batcher.get_table()+ # Checkpoint the cursor that fetched the current page; on resume we+ # re-fetch it and rely on primary-key merge semantics to dedupe.+ manager.save_state(TrelloResumeConfig(board_index=index, before_cursor=before))++ if len(data) < config.page_size or not oldest_id:+ break++ before = oldest_id+ manager.save_state(TrelloResumeConfig(board_index=index, before_cursor=before))++ manager.save_state(TrelloResumeConfig(board_index=index + 1, before_cursor=None))+++def _sync_board_endpoint(+ config: TrelloEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[TrelloResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ board_ids = _fetch_board_ids(headers, logger)++ resume = manager.load_state() if manager.can_resume() else None+ start_index = resume.board_index if resume else 0+ resume_before = resume.before_cursor if resume else None+ if resume is not None:+ logger.debug(f"Trello: resuming {config.name} from board index {start_index}")++ since: str | None = None+ if config.paginated and should_use_incremental_field and db_incremental_field_last_value:+ since = _format_incremental_value(db_incremental_field_last_value)++ for index in range(start_index, len(board_ids)):+ board_id = board_ids[index]+ if config.paginated:+ # Only the board we resumed into carries an in-progress before cursor.+ before = resume_before if index == start_index else None+ yield from _sync_board_actions(board_id, index, config, headers, logger, batcher, manager, since, before)+ else:+ yield from _sync_board_simple(board_id, index, config, headers, logger, batcher, manager)+++def get_rows(+ api_key: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TrelloResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = TRELLO_ENDPOINTS[endpoint]+ headers = _get_headers(api_key, api_token)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ if config.scope == "member":+ yield from _sync_member_endpoint(config, headers, logger, batcher)+ else:+ yield from _sync_board_endpoint(+ config,+ headers,+ logger,+ batcher,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def trello_source(+ api_key: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TrelloResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = TRELLO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[endpoint_config.primary_key],+ sort_mode=endpoint_config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )