: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 shortcut import source (#61163)
Tom Owersbdb9e4beac18
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 9300b982ae87..d8bc8dc1a74c 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -79,6 +79,7 @@ the row lists both.| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ || sentry | HTTP | requests + `rest_source.RESTClient` | ✅ || shopify | HTTP | requests | ✅ |+| shortcut | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ || snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || snowflake | DB protocol | snowflake-connector-python | ➖ |@@ -127,7 +128,7 @@ fullstory, gitlab, gong, google_analytics, google_drive, gorgias, granola, greeninstagram, intercom, iterable, jira, kafka, launchdarkly, lever, mailerlite, mailjet, marketo,microsoft_teams, mixpanel, monday, netsuite, notion, okta, omnisend, onedrive, oracle, outreach,pagerduty, pardot, paypal, pendo, pipedrive, plaid, postmark, productboard, quickbooks, recharge,-recurly, ringcentral, salesloft, sendgrid, servicenow, sftp, sharepoint, shortcut, smartsheet,+recurly, ringcentral, salesloft, sendgrid, servicenow, sftp, sharepoint, smartsheet,square, surveymonkey, trello, twilio, twitter_ads, webflow, woocommerce, workday, wrike, xero,youtube_analytics, zoho_crm, zoom, zuora.diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex a5016d4cf71f..6037c00bcfb8 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -754,7 +754,7 @@ class ShopifySourceConfig(config.Config):@config.configclass ShortcutSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/shortcut/api_inventory.md b/posthog/temporal/data_imports/sources/shortcut/api_inventory.mdnew file mode 100644index 000000000000..2daa91f6a6ac--- /dev/null+++ b/posthog/temporal/data_imports/sources/shortcut/api_inventory.md@@ -0,0 +1,62 @@+# Shortcut API v3 — endpoint inventory++Base URL: `https://api.app.shortcut.com/api/v3`+Auth: `Shortcut-Token: <token>` header (workspace-scoped token; token dies if the user leaves the workspace).+Rate limit: 200 requests/minute → `429` on excess (no documented rate-limit response headers).++Derived from the authoritative v3 OpenAPI spec (`https://developer.shortcut.com/api/rest/v3/shortcut.openapi.json`).++> **Verification gap:** these notes come from the OpenAPI spec only. We did not have a live workspace+> token to curl-verify behavior (per the implementing-warehouse-sources skill). The flat-list facts below+> are low-risk (the spec defines no filter/pagination params at all). The one item to revisit once a token+> is available is the `stories` incremental filter (see below).++## Flat list endpoints (full refresh)++Each returns the **entire collection in a single un-paginated JSON array** and accepts **no server-side+timestamp filter** — so they are full-refresh only. All carry `created_at` (stable, used as the partition+key) and `updated_at`.++| Schema | Path | PK `id` type |+| ---------------- | ------------------- | ------------- |+| members | `/members` | string (UUID) |+| groups | `/groups` | string (UUID) |+| projects | `/projects` | integer |+| workflows | `/workflows` | integer |+| epics | `/epics` | integer |+| iterations | `/iterations` | integer |+| labels | `/labels` | integer |+| categories | `/categories` | integer |+| objectives | `/objectives` | integer |+| custom_fields | `/custom-fields` | string (UUID) |+| files | `/files` | integer |+| linked_files | `/linked-files` | integer |+| repositories | `/repositories` | integer |+| entity_templates | `/entity-templates` | string (UUID) |++`primary_keys=["id"]` works for all (the field name is uniform; only the value type differs).++## stories (incremental)++There is **no top-level `GET /stories`** list endpoint. Stories are fetched via **`POST /stories/search`**+("Query Stories"), which accepts structured server-side filters including `created_at_start` /+`updated_at_start` and returns a **plain JSON array of `StorySlim`** (no pagination wrapper, no documented+result cap). We map the user's chosen incremental field to the matching `*_start` filter.++- Incremental field options: `updated_at` (default) and `created_at`.+- Partition key: `created_at`.++**Revisit with a live token:** confirm that (a) `updated_at_start` actually filters server-side rather than+being silently ignored, and (b) the accepted date format (we send RFC 3339 `...Z`). If the filter is+ignored, the sync still produces correct data (merge dedupes on `id`) but every run refetches all stories.+For very large workspaces, a future improvement is to window `POST /stories/search` by `created_at` ranges,+since the endpoint exposes no pagination.++## Webhooks (deferred)++Shortcut supports a single programmatic "generic integration" webhook+(`POST`/`GET`/`DELETE /integrations/webhook[/{id}]`) with optional HMAC-SHA-256 `Payload-Signature`+verification. It is **not** wired up here because the webhook payload is a **change log** (`actions[]` with+partial diffs and `entity_type`), not full entity records — it doesn't map onto the per-table row model the+`WebhookSource` base expects without an extra per-event entity refetch, and we couldn't validate the payload+shape against a live workspace. Pull-based sync is the alpha scope.diff --git a/posthog/temporal/data_imports/sources/shortcut/settings.py b/posthog/temporal/data_imports/sources/shortcut/settings.pynew file mode 100644index 000000000000..85b627c11680--- /dev/null+++ b/posthog/temporal/data_imports/sources/shortcut/settings.py@@ -0,0 +1,72 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class ShortcutEndpointConfig:+ name: str+ path: str+ # The flat list endpoints are plain GETs that return the whole collection. Stories have+ # no top-level list endpoint, so they're fetched via `POST /stories/search`.+ method: str = "GET"+ primary_key: str = "id"+ # Stable field used for datetime partitioning. Never `updated_at` — partitions must not move.+ partition_key: Optional[str] = "created_at"+ # Map of incremental field name -> the server-side timestamp filter param it maps to.+ # Empty for full-refresh endpoints. Shortcut's flat list endpoints expose no server-side+ # timestamp filter (verified against the v3 OpenAPI spec), so only `stories` is incremental.+ incremental_params: dict[str, str] = field(default_factory=dict)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Endpoint catalog. All flat collections are full-refresh: the Shortcut v3 API returns each+# in a single un-paginated response and accepts no server-side timestamp filter, so there is+# nothing to page through or filter incrementally. `stories` is the exception — it's queried+# through `POST /stories/search`, which accepts real server-side `created_at_start` /+# `updated_at_start` filters.+SHORTCUT_ENDPOINTS: dict[str, ShortcutEndpointConfig] = {+ "members": ShortcutEndpointConfig(name="members", path="/members"),+ "groups": ShortcutEndpointConfig(name="groups", path="/groups"),+ "projects": ShortcutEndpointConfig(name="projects", path="/projects"),+ "workflows": ShortcutEndpointConfig(name="workflows", path="/workflows"),+ "epics": ShortcutEndpointConfig(name="epics", path="/epics"),+ "iterations": ShortcutEndpointConfig(name="iterations", path="/iterations"),+ "labels": ShortcutEndpointConfig(name="labels", path="/labels"),+ "categories": ShortcutEndpointConfig(name="categories", path="/categories"),+ "objectives": ShortcutEndpointConfig(name="objectives", path="/objectives"),+ "custom_fields": ShortcutEndpointConfig(name="custom_fields", path="/custom-fields"),+ "files": ShortcutEndpointConfig(name="files", path="/files"),+ "linked_files": ShortcutEndpointConfig(name="linked_files", path="/linked-files"),+ "repositories": ShortcutEndpointConfig(name="repositories", path="/repositories"),+ "entity_templates": ShortcutEndpointConfig(name="entity_templates", path="/entity-templates"),+ "stories": ShortcutEndpointConfig(+ name="stories",+ path="/stories/search",+ method="POST",+ incremental_params={+ "updated_at": "updated_at_start",+ "created_at": "created_at_start",+ },+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ ),+}++ENDPOINTS = tuple(SHORTCUT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SHORTCUT_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/shortcut/shortcut.py b/posthog/temporal/data_imports/sources/shortcut/shortcut.pynew file mode 100644index 000000000000..b87179078eb4--- /dev/null+++ b/posthog/temporal/data_imports/sources/shortcut/shortcut.py@@ -0,0 +1,161 @@+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from requests.exceptions import RequestException+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.shortcut.settings import SHORTCUT_ENDPOINTS, ShortcutEndpointConfig++SHORTCUT_BASE_URL = "https://api.app.shortcut.com/api/v3"+REQUEST_TIMEOUT = 60+MAX_RETRIES = 5+++class ShortcutRetryableError(Exception):+ """Raised for transient Shortcut API failures (429 / 5xx) so tenacity retries them."""++ pass+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Shortcut-Token": api_token,+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value for Shortcut's `*_start` search filters (RFC 3339)."""+ if isinstance(value, datetime):+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d")+ return str(value)+++def _build_search_body(+ config: ShortcutEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Build the JSON body for `POST /stories/search`.++ Maps the user-selected incremental field to the matching server-side filter param.+ An empty body returns the full collection (initial sync / full refresh).+ """+ body: dict[str, Any] = {}+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ field_name = incremental_field or "updated_at"+ param = config.incremental_params.get(field_name)+ if param:+ body[param] = _format_incremental_value(db_incremental_field_last_value)+ return body+++def _parse_response(response: requests.Response, url: str, logger: FilteringBoundLogger) -> Any:+ """Classify a Shortcut response: retry on 429/5xx, fail on other 4xx, else return JSON."""+ # Shortcut returns 429 when the 200 req/min limit is exceeded, without documented+ # rate-limit headers, so we fall back to exponential backoff for those (and 5xx).+ if response.status_code == 429 or response.status_code >= 500:+ raise ShortcutRetryableError(f"Shortcut API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Shortcut API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ """Probe the cheapest authenticated endpoint to confirm the token is genuine."""+ url = f"{SHORTCUT_BASE_URL}/member"+ try:+ with make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,)) as session:+ response = session.get(url, timeout=10)+ except RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Shortcut API token. Generate a new token in Settings > API Tokens and reconnect."+ if response.status_code == 403:+ return False, "Your Shortcut API token does not have access to this workspace. Please check its permissions."+ return False, f"Shortcut API returned an unexpected status: {response.status_code}"+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = SHORTCUT_ENDPOINTS[endpoint]+ url = f"{SHORTCUT_BASE_URL}{config.path}"++ with make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,)) as session:++ @retry(+ retry=retry_if_exception_type((ShortcutRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch(method: str, body: Optional[dict[str, Any]]) -> Any:+ response = session.request(method, url, json=body, timeout=REQUEST_TIMEOUT)+ return _parse_response(response, url, logger)++ if config.method == "POST":+ body = _build_search_body(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ data = fetch("POST", body)+ else:+ data = fetch("GET", None)++ # Every Shortcut list endpoint (and the stories search) returns a bare JSON array.+ if not isinstance(data, list):+ logger.warning(f"Shortcut endpoint {endpoint} returned a non-list response; skipping")+ return++ if data:+ yield data+++def shortcut_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = SHORTCUT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=[config.primary_key],+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/shortcut/source.py b/posthog/temporal/data_imports/sources/shortcut/source.pyindex c7b2caf60abb..32bd73887646 100644--- a/posthog/temporal/data_imports/sources/shortcut/source.py+++ b/posthog/temporal/data_imports/sources/shortcut/source.py@@ -1,13 +1,23 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponsefrom posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import ShortcutSourceConfig+from posthog.temporal.data_imports.sources.shortcut.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.shortcut.shortcut import (+ shortcut_source,+ validate_credentials as validate_shortcut_credentials,+)from products.data_warehouse.backend.types import ExternalDataSourceType@@ -23,7 +33,68 @@ class ShortcutSource(SimpleSource[ShortcutSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.SHORTCUT,label="Shortcut",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Shortcut API token to sync your Shortcut data into the PostHog Data warehouse.++You can create an API token in your [Shortcut account settings](https://app.shortcut.com/settings/account/api-tokens). The token grants access to the whole workspace it belongs to and becomes invalid if you're removed from that workspace.""",iconPath="/static/services/shortcut.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/shortcut",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: ShortcutSourceConfig,+ 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 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 get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid or expired Shortcut API token. Please generate a new token and reconnect.",+ "403 Client Error": "Your Shortcut API token does not have access to this workspace. Please check its permissions.",+ }++ def validate_credentials(+ self, config: ShortcutSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_shortcut_credentials(config.api_token)++ def source_for_pipeline(self, config: ShortcutSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return shortcut_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/shortcut/tests/test_shortcut.py b/posthog/temporal/data_imports/sources/shortcut/tests/test_shortcut.pynew file mode 100644index 000000000000..4a301bc0abec--- /dev/null+++ b/posthog/temporal/data_imports/sources/shortcut/tests/test_shortcut.py@@ -0,0 +1,196 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from requests import Response+from requests.exceptions import HTTPError++from posthog.temporal.data_imports.sources.shortcut.settings import ENDPOINTS, SHORTCUT_ENDPOINTS+from posthog.temporal.data_imports.sources.shortcut.shortcut import (+ SHORTCUT_BASE_URL,+ ShortcutRetryableError,+ _build_search_body,+ _format_incremental_value,+ _parse_response,+ get_rows,+ shortcut_source,+ validate_credentials,+)+++def _make_response(json_data: Any = None, status_code: int = 200) -> mock.Mock:+ response = mock.Mock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = json_data+ response.text = str(json_data)+ error_response = Response()+ error_response.status_code = status_code+ response.raise_for_status = mock.Mock(side_effect=HTTPError(f"{status_code} Client Error", response=error_response))+ return response+++class TestFormatIncrementalValue:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ (date(2026, 3, 4), "2026-03-04"),+ ("2026-03-04T00:00:00Z", "2026-03-04T00:00:00Z"),+ ],+ )+ def test_format(self, value: Any, expected: str) -> None:+ result = _format_incremental_value(value)+ assert result == expected+ assert "+00:00" not in result+++class TestBuildSearchBody:+ def test_no_incremental_returns_empty_body(self) -> None:+ body = _build_search_body(SHORTCUT_ENDPOINTS["stories"], False, None, None)+ assert body == {}++ def test_incremental_without_last_value_returns_empty_body(self) -> None:+ body = _build_search_body(SHORTCUT_ENDPOINTS["stories"], True, None, "updated_at")+ assert body == {}++ @pytest.mark.parametrize(+ "incremental_field, expected_param",+ [+ ("updated_at", "updated_at_start"),+ ("created_at", "created_at_start"),+ (None, "updated_at_start"),+ ],+ )+ def test_maps_field_to_server_side_filter(self, incremental_field: str | None, expected_param: str) -> None:+ body = _build_search_body(+ SHORTCUT_ENDPOINTS["stories"], True, datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), incremental_field+ )+ assert body == {expected_param: "2026-01-02T03:04:05Z"}++ def test_full_refresh_endpoint_has_no_filter_params(self) -> None:+ # Flat list endpoints expose no incremental params, so even with a cursor we send nothing.+ body = _build_search_body(SHORTCUT_ENDPOINTS["members"], True, datetime(2026, 1, 1, tzinfo=UTC), "updated_at")+ assert body == {}+++class TestParseResponse:+ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])+ def test_retryable_statuses_raise(self, status_code: int) -> None:+ with pytest.raises(ShortcutRetryableError):+ _parse_response(_make_response(status_code=status_code), "url", mock.Mock())++ @pytest.mark.parametrize("status_code", [400, 401, 403, 404])+ def test_client_errors_raise_for_status(self, status_code: int) -> None:+ with pytest.raises(HTTPError):+ _parse_response(_make_response(status_code=status_code), "url", mock.Mock())++ def test_success_returns_json(self) -> None:+ result = _parse_response(_make_response(json_data=[{"id": 1}]), "url", mock.Mock())+ assert result == [{"id": 1}]+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_valid",+ [+ (200, True),+ (401, False),+ (403, False),+ (418, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.shortcut.shortcut.make_tracked_session")+ def test_status_mapping(self, mock_session_factory, status_code: int, expected_valid: bool) -> None:+ session = mock.Mock()+ session.get.return_value = _make_response(json_data={"id": "x"}, status_code=status_code)+ mock_session_factory.return_value.__enter__.return_value = session++ is_valid, error = validate_credentials("token")++ assert is_valid is expected_valid+ if expected_valid:+ assert error is None+ else:+ assert error is not None+ session.get.assert_called_once()+ assert session.get.call_args[0][0] == f"{SHORTCUT_BASE_URL}/member"+++class TestGetRows:+ @mock.patch("posthog.temporal.data_imports.sources.shortcut.shortcut.make_tracked_session")+ def test_get_endpoint_yields_full_list(self, mock_session_factory) -> None:+ session = mock.Mock()+ rows = [{"id": 1}, {"id": 2}]+ session.request.return_value = _make_response(json_data=rows)+ mock_session_factory.return_value.__enter__.return_value = session++ batches = list(get_rows("token", "members", mock.Mock()))++ assert batches == [rows]+ method, url = session.request.call_args[0]+ assert method == "GET"+ assert url == f"{SHORTCUT_BASE_URL}/members"+ assert session.request.call_args.kwargs["json"] is None++ @mock.patch("posthog.temporal.data_imports.sources.shortcut.shortcut.make_tracked_session")+ def test_stories_uses_post_with_incremental_body(self, mock_session_factory) -> None:+ session = mock.Mock()+ session.request.return_value = _make_response(json_data=[{"id": 10}])+ mock_session_factory.return_value.__enter__.return_value = session++ batches = list(+ get_rows(+ "token",+ "stories",+ mock.Mock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ incremental_field="updated_at",+ )+ )++ assert batches == [[{"id": 10}]]+ method, url = session.request.call_args[0]+ assert method == "POST"+ assert url == f"{SHORTCUT_BASE_URL}/stories/search"+ assert session.request.call_args.kwargs["json"] == {"updated_at_start": "2026-01-02T03:04:05Z"}++ @mock.patch("posthog.temporal.data_imports.sources.shortcut.shortcut.make_tracked_session")+ def test_empty_list_yields_nothing(self, mock_session_factory) -> None:+ session = mock.Mock()+ session.request.return_value = _make_response(json_data=[])+ mock_session_factory.return_value.__enter__.return_value = session++ assert list(get_rows("token", "epics", mock.Mock())) == []++ @mock.patch("posthog.temporal.data_imports.sources.shortcut.shortcut.make_tracked_session")+ def test_non_list_response_yields_nothing(self, mock_session_factory) -> None:+ session = mock.Mock()+ session.request.return_value = _make_response(json_data={"unexpected": "shape"})+ mock_session_factory.return_value.__enter__.return_value = session+ logger = mock.Mock()++ assert list(get_rows("token", "epics", logger)) == []+ logger.warning.assert_called_once()+++class TestShortcutSource:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_response_shape(self, endpoint: str) -> None:+ response = shortcut_source("token", endpoint, mock.Mock())++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Every endpoint partitions on the stable created_at field.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ assert response.partition_format == "month"++ def test_stories_is_the_only_incremental_endpoint(self) -> None:+ # Sanity check that mirrors the schema-level contract in the settings catalog.+ incremental = {name for name, cfg in SHORTCUT_ENDPOINTS.items() if cfg.incremental_params}+ assert incremental == {"stories"}diff --git a/posthog/temporal/data_imports/sources/shortcut/tests/test_shortcut_source.py b/posthog/temporal/data_imports/sources/shortcut/tests/test_shortcut_source.pynew file mode 100644index 000000000000..2b037c209466--- /dev/null+++ b/posthog/temporal/data_imports/sources/shortcut/tests/test_shortcut_source.py@@ -0,0 +1,142 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.generated_configs import ShortcutSourceConfig+from posthog.temporal.data_imports.sources.shortcut.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.shortcut.source import ShortcutSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestShortcutSource:+ def setup_method(self):+ self.source = ShortcutSource()+ self.team_id = 123+ self.config = ShortcutSourceConfig(api_token="test-token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.SHORTCUT++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Shortcut"+ assert config.label == "Shortcut"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/shortcut.png"+ 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+ assert token_field.secret is True++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_only_stories_supports_incremental(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["stories"].supports_incremental is True+ assert schemas["stories"].supports_append is True+ # Story incremental fields are updated_at (default) and created_at.+ assert {f["field"] for f in schemas["stories"].incremental_fields} == {"updated_at", "created_at"}++ for name, schema in schemas.items():+ if name == "stories":+ continue+ assert schema.supports_incremental is False, name+ assert schema.supports_append is False, name+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["members"])+ assert len(schemas) == 1+ assert schemas[0].name == "members"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["nonexistent"])+ assert schemas == []++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.app.shortcut.com/api/v3/members",+ "403 Client Error: Forbidden for url: https://api.app.shortcut.com/api/v3/stories/search",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests",+ "500 Server Error: Internal Server Error",+ ],+ )+ def test_non_retryable_errors_ignore_transient_failures(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, None), True, None),+ ((False, "Invalid Shortcut API token."), False, "Invalid Shortcut API token."),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.shortcut.source.validate_shortcut_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_token)++ def test_source_for_pipeline_plumbs_arguments(self):+ inputs = mock.Mock()+ inputs.schema_name = "stories"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "updated_at"+ inputs.logger = mock.Mock()++ with mock.patch(+ "posthog.temporal.data_imports.sources.shortcut.source.shortcut_source"+ ) as mock_shortcut_source:+ self.source.source_for_pipeline(self.config, inputs)++ mock_shortcut_source.assert_called_once_with(+ api_token="test-token",+ endpoint="stories",+ logger=inputs.logger,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="updated_at",+ )++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self):+ inputs = mock.Mock()+ inputs.schema_name = "members"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "should-be-ignored"+ inputs.incremental_field = None+ inputs.logger = mock.Mock()++ with mock.patch(+ "posthog.temporal.data_imports.sources.shortcut.source.shortcut_source"+ ) as mock_shortcut_source:+ self.source.source_for_pipeline(self.config, inputs)++ _, kwargs = mock_shortcut_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None