: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): add Dovetail source (#73193)
Tom Owers5d34a67c7e60
diff --git a/frontend/public/services/dovetail.png b/frontend/public/services/dovetail.pngindex af6bda0861da..8687ee38a957 100644Binary files a/frontend/public/services/dovetail.png and b/frontend/public/services/dovetail.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b86b60767b25..6e6a696d026f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -189,6 +189,7 @@ the row lists both.| docuseal | HTTP | requests | ✅ || doit | HTTP | requests | ✅ || doppler | HTTP | requests | ✅ |+| dovetail | HTTP | requests + `rest_source.RESTClient` | ✅ || drata | HTTP | requests | ✅ || dropbox_sign | HTTP | requests | ✅ || drip | HTTP | requests | ✅ |@@ -878,7 +879,6 @@ doesn't conflict with concurrent PRs.- donorbox- doorloop- doppler-- dovetail- drata- drchrono- dremiodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/canonical_descriptions.pynew file mode 100644index 000000000000..ebd65a018124--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/canonical_descriptions.py@@ -0,0 +1,128 @@+"""Canonical, documentation-sourced descriptions for Dovetail endpoints and columns.++Sourced from the official Dovetail REST API reference (https://developers.dovetail.com/reference).+Keyed by the resource names in `settings.py` `DOVETAIL_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Dovetail table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Projects": {+ "description": "A Dovetail project - the top-level container for organizing qualitative "+ "research, holding data, docs, highlights, tags, and insights related to a specific "+ "research initiative.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "url": "URL of the project in the Dovetail web app.",+ "title": "Title of the project.",+ "type": "Resource type, always 'project'.",+ "author": "The user who created the project (id and name).",+ "created_at": "Time at which the project was created, in ISO 8601 format.",+ "deleted": "Whether the project has been deleted.",+ "folder": "The folder containing the project, if any (id).",+ },+ },+ "Data": {+ "description": "A piece of research data (interview transcript, note, or other captured "+ "customer feedback) stored in Dovetail. Metadata only - the content body is not included "+ "and must be fetched via the export endpoint.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-data",+ "columns": {+ "id": "Unique identifier for the data entry.",+ "url": "URL of the data entry in the Dovetail web app.",+ "title": "Title of the data entry.",+ "type": "Resource type, always 'data'.",+ "project": "The project the data entry belongs to (id and title).",+ "created_at": "Time at which the data entry was created, in ISO 8601 format.",+ "deleted": "Whether the data entry has been deleted.",+ "folder": "The folder containing the data entry, if any (id).",+ },+ },+ "Docs": {+ "description": "A Dovetail doc - a synthesized research artifact (report, insight, or "+ "written analysis). Metadata only - the document body is not included and must be "+ "fetched via the export endpoint.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-docs",+ "columns": {+ "id": "Unique identifier for the doc.",+ "url": "URL of the doc in the Dovetail web app.",+ "title": "Title of the doc.",+ "type": "Resource type, always 'doc'.",+ "created_at": "Time at which the doc was created, in ISO 8601 format.",+ "folder": "The folder containing the doc, if any (id).",+ },+ },+ "Highlights": {+ "description": "A highlight - a tagged excerpt of a transcript or note captured during "+ "qualitative analysis, optionally categorized with one or more tags.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-highlights",+ "columns": {+ "id": "Unique identifier for the highlight.",+ "url": "URL of the parent note containing this highlight in the Dovetail web app.",+ "note_id": "Identifier of the note (data entry) the highlight belongs to, if any.",+ "tags": "Tags applied to the highlight (id and title for each).",+ "text": "Text content of the highlight excerpt.",+ "type": "Resource type, always 'highlight'.",+ "start_time": "Start timestamp (seconds) of the highlight within its source media, if any.",+ "end_time": "End timestamp (seconds) of the highlight within its source media, if any.",+ "created_at": "Time at which the highlight was created, in ISO 8601 format.",+ "updated_at": "Time at which the highlight was last updated, in ISO 8601 format.",+ },+ },+ "Tags": {+ "description": "A tag used to categorize highlights during qualitative analysis (e.g. "+ "'Usability Issue', 'Feature Request'). Each tag belongs to a specific project.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-tags",+ "columns": {+ "id": "Unique identifier for the tag.",+ "url": "URL of the tag in the Dovetail web app.",+ "title": "Title (label) of the tag.",+ "project_id": "Identifier of the project the tag belongs to.",+ "created_at": "Time at which the tag was created, in ISO 8601 format.",+ },+ },+ "Contacts": {+ "description": "A contact - a research participant or customer tracked in Dovetail's "+ "contact management, with custom field values.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-contacts",+ "columns": {+ "id": "Unique identifier for the contact.",+ "url": "URL of the contact in the Dovetail web app.",+ "name": "Name of the contact.",+ "created_at": "Time at which the contact was created, in ISO 8601 format.",+ "fields": "Custom field values associated with the contact (label, value, and type per field).",+ },+ },+ "Users": {+ "description": "A user (team member) with access to the Dovetail workspace.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-users",+ "columns": {+ "id": "Unique identifier for the user.",+ "url": "URL of the user in the Dovetail web app.",+ "name": "Name of the user.",+ "email": "Email address of the user.",+ "job_title": "Job title of the user, if set.",+ "role": "Workspace role of the user: CONTRIBUTOR, MANAGER, or VIEWER.",+ "workspace_admin": "Whether the user is a workspace administrator.",+ "created_at": "Time at which the user was created, in ISO 8601 format.",+ "updated_at": "Time at which the user was last updated, in ISO 8601 format.",+ },+ },+ "DocComments": {+ "description": "A comment left on a Dovetail doc, aggregated across every doc in the workspace.",+ "docs_url": "https://developers.dovetail.com/reference/get_v1-docs-doc-id-comments",+ "columns": {+ "id": "Unique identifier for the comment.",+ "doc_id": "Identifier of the doc the comment belongs to.",+ "url": "URL of the doc this comment belongs to in the Dovetail web app.",+ "body": "Text content of the comment.",+ "author": "The user who wrote the comment (id and name).",+ "created_at": "Time at which the comment was created, in ISO 8601 format.",+ "updated_at": "Time at which the comment was last updated, in ISO 8601 format.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/dovetail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/dovetail.pynew file mode 100644index 000000000000..42fdb0422e37--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/dovetail.py@@ -0,0 +1,205 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional, cast++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ PaginatorConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.settings import (+ DOVETAIL_BASE_URL,+ DOVETAIL_ENDPOINTS,+ DovetailEndpointConfig,+)+++class DovetailResumeConfig:+ # Opaque framework checkpoint: `{"cursor": ...}` for a top-level endpoint's+ # JSONResponseCursorPaginator, or the fan-out manager's `{"completed": [...], "current":+ # ..., "child_state": {...}}` for DocComments - round-tripped into+ # `initial_paginator_state` on resume.+ paginator_state: dict[str, Any]+++def _paginator_config() -> PaginatorConfig:+ return {+ "type": "cursor",+ "cursor_path": "page.next_cursor",+ "cursor_param": "page[start_cursor]",+ }+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": DOVETAIL_BASE_URL,+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ }+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor as ISO 8601, which Dovetail's `filter[<field>][gte]` expects."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _incremental_filter_param(cursor_field: str) -> dict[str, Any]:+ return {+ "type": "incremental",+ "cursor_path": cursor_field,+ "initial_value": None,+ "convert": _format_incremental_value,+ }+++def get_resource(name: str, should_use_incremental_field: bool, incremental_field: str | None) -> EndpointResource:+ config = DOVETAIL_ENDPOINTS[name]+ cursor_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)+ use_incremental = should_use_incremental_field and cursor_field is not None++ params: dict[str, Any] = {+ "page[limit]": config.page_size,+ # Dovetail defaults every list endpoint to `created_at:desc`; sort ascending explicitly+ # so the incremental watermark advances monotonically (and, for full-refresh endpoints,+ # so page boundaries stay stable if rows are inserted mid-sync).+ "sort": "created_at:asc",+ }+ if cursor_field is not None:+ params[f"filter[{cursor_field}][gte]"] = _incremental_filter_param(cursor_field) if use_incremental else None++ endpoint: Endpoint = {+ "path": config.path,+ "data_selector": "data",+ "params": params,+ "paginator": _paginator_config(),+ }++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": ({"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace"),+ "endpoint": endpoint,+ "table_format": "delta",+ }+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{DOVETAIL_BASE_URL}/v1/token/info",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ )+ if ok:+ return True, None+ if status == 401:+ return False, "Dovetail rejected the API token. Please generate a new personal API key and reconnect."+ if status == 403:+ return False, "Your Dovetail API token does not have permission for this resource."+ if status is None:+ return False, "Could not reach Dovetail. Please check your network and try again."+ return False, f"Dovetail API returned an unexpected status: {status}"+++def _make_source_response(endpoint_config: DovetailEndpointConfig, items_fn: Any) -> SourceResponse:+ return SourceResponse(+ name=endpoint_config.name,+ items=items_fn,+ primary_keys=(+ endpoint_config.primary_key+ if isinstance(endpoint_config.primary_key, list)+ else [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="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def dovetail_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[DovetailResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = DOVETAIL_ENDPOINTS[endpoint]++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = resume_config.paginator_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's somewhere to resume to; the manager's 24h Redis TTL+ # handles cleanup once a sync completes.+ if state:+ resumable_source_manager.save_state(DovetailResumeConfig(paginator_state=dict(state)))++ if endpoint_config.fanout:+ # DocComments has no server-side filter of its own, so every sync walks the full Docs+ # list to discover doc ids and re-fetches comments per doc; that's inherent to the API+ # (no workspace-wide comments-list endpoint exists) and mirrors other fan-out sources.+ dependent_resource = build_dependent_resource(+ endpoint_configs=cast(Any, DOVETAIL_ENDPOINTS),+ child_endpoint=endpoint,+ fanout=endpoint_config.fanout,+ client_config=_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param="page[limit]",+ parent_endpoint_extra={+ "paginator": _paginator_config(),+ "data_selector": "data",+ },+ child_endpoint_extra={+ "paginator": _paginator_config(),+ "data_selector": "data",+ },+ child_params_extra={"sort": "created_at:asc"},+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return _make_source_response(endpoint_config, lambda: dependent_resource)++ config: RESTAPIConfig = {+ "client": _client_config(api_key),+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],+ }++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return _make_source_response(endpoint_config, lambda: resource)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/settings.pynew file mode 100644index 000000000000..f425f1af1478--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/settings.py@@ -0,0 +1,90 @@+from dataclasses import dataclass, field+from typing import Literal++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Endpoint paths below already carry the `/v1` segment (matching the official OpenAPI spec's+# `servers` entry), so the base URL stops at `/api`.+DOVETAIL_BASE_URL = "https://dovetail.com/api"++# Dovetail's `page[limit]` caps at 100 items/request (see+# https://developers.dovetail.com/docs/pagination).+PAGE_SIZE = 100+++@dataclass+class DovetailEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ partition_key: str | None = "created_at"+ page_size: int = PAGE_SIZE+ sort_mode: Literal["asc", "desc"] = "asc"+ primary_key: str | list[str] = "id"+ fanout: DependentEndpointConfig | None = None+++DOVETAIL_ENDPOINTS: dict[str, DovetailEndpointConfig] = {+ # Projects, Tags, Contacts, and Users have no server-side date filter (only `page`/`sort`,+ # plus non-date filters like `folder_id`/`title`/`name`), so these are full refresh only.+ "Projects": DovetailEndpointConfig(+ name="Projects",+ path="/v1/projects",+ ),+ "Data": DovetailEndpointConfig(+ name="Data",+ path="/v1/data",+ incremental_fields=[incremental_field("created_at")],+ ),+ "Docs": DovetailEndpointConfig(+ name="Docs",+ path="/v1/docs",+ incremental_fields=[incremental_field("created_at")],+ ),+ "Highlights": DovetailEndpointConfig(+ name="Highlights",+ path="/v1/highlights",+ # Highlights also expose `filter[updated_at]`, but the endpoint's `sort` param only+ # offers `created_at:asc`/`created_at:desc` (verified against the live OpenAPI spec) -+ # there is no way to have the API return rows in updated_at order, so updated_at is not+ # safe to advertise as an incremental cursor (sort_mode would not match arrival order).+ incremental_fields=[incremental_field("created_at")],+ ),+ "Tags": DovetailEndpointConfig(+ name="Tags",+ path="/v1/tags",+ ),+ "Contacts": DovetailEndpointConfig(+ name="Contacts",+ path="/v1/contacts",+ ),+ "Users": DovetailEndpointConfig(+ name="Users",+ path="/v1/users",+ ),+ "DocComments": DovetailEndpointConfig(+ name="DocComments",+ path="/v1/docs/{doc_id}/comments",+ # Comment ids are only documented per-doc; this table aggregates comments across every+ # doc in the workspace, so the parent doc id is part of the key to keep it unique+ # table-wide.+ primary_key=["doc_id", "id"],+ fanout=DependentEndpointConfig(+ parent_name="Docs",+ resolve_param="doc_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "doc_id"},+ ),+ ),+}++ENDPOINTS = tuple(DOVETAIL_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DOVETAIL_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/source.pyindex a0c8e9031ac2..b20816917dc4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/source.py@@ -1,13 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.dovetail import (+ DovetailResumeConfig,+ dovetail_source,+ validate_credentials as validate_dovetail_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dovetail import (DovetailSourceConfig,)@@ -15,18 +39,93 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DovetailSource(SimpleSource[DovetailSourceConfig]):+class DovetailSource(ResumableSource[DovetailSourceConfig, DovetailResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Dovetail's API has no versioned path/header (a bare `/v1/` that's never changed and isn't a+ # documented version choice) - only the docs URL is worth pinning.+ api_docs_url = "https://developers.dovetail.com/docs/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DOVETAIL+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Dovetail rejected the API token. Please generate a new personal API key from workspace settings and reconnect.",+ "403 Client Error: Forbidden for url": "Your Dovetail API token does not have permission for this resource.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: DovetailSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: DovetailSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_dovetail_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DovetailResumeConfig]:+ return ResumableSourceManager[DovetailResumeConfig](inputs, DovetailResumeConfig)++ def source_for_pipeline(+ self,+ config: DovetailSourceConfig,+ resumable_source_manager: ResumableSourceManager[DovetailResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return dovetail_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DOVETAIL,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Dovetail",+ docsUrl="https://posthog.com/docs/cdp/sources/dovetail",iconPath="/static/services/dovetail.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["user research", "customer research", "qualitative research"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ caption="Generate a personal API key from **Settings > Account > Personal API keys** in Dovetail.",+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/tests/test_dovetail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/tests/test_dovetail.pynew file mode 100644index 000000000000..4d772aa28cc0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/tests/test_dovetail.py@@ -0,0 +1,299 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, Optional, cast++import pytest++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.dovetail import (+ DovetailResumeConfig,+ _format_incremental_value,+ dovetail_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.settings import DOVETAIL_BASE_URL++BASE_URL = DOVETAIL_BASE_URL+++class _FakeResumeManager(ResumableSourceManager[DovetailResumeConfig]):+ # In-memory stand-in — deliberately doesn't call super().__init__, so no Redis is touched.+ def __init__(self, state: Optional[dict[str, Any]] = None) -> None:+ self._state = state+ self.saved: list[dict[str, Any]] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> Optional[DovetailResumeConfig]:+ return DovetailResumeConfig(paginator_state=self._state) if self._state is not None else None++ def save_state(self, data: DovetailResumeConfig) -> None:+ self.saved.append(data.paginator_state)+++def _collect_rows(response: SourceResponse) -> list[dict[str, Any]]:+ items = response.items()+ assert isinstance(items, Iterable)+ pages = cast(list[list[dict[str, Any]]], list(items))+ return [row for page in pages for row in page]+++class TestValidateCredentials:+ def test_valid_token(self, requests_mock: Any) -> None:+ requests_mock.get(f"{BASE_URL}/v1/token/info", json={"data": {"id": "tok1", "subdomain": "acme"}})++ result = validate_credentials("tok")++ assert result == (True, None)+ assert requests_mock.last_request.headers["Authorization"] == "Bearer tok"++ @pytest.mark.parametrize(+ "status,expected_message",+ [+ (401, "Dovetail rejected the API token. Please generate a new personal API key and reconnect."),+ (403, "Your Dovetail API token does not have permission for this resource."),+ (500, "Dovetail API returned an unexpected status: 500"),+ ],+ )+ def test_status_mapping(self, status: int, expected_message: str, requests_mock: Any) -> None:+ requests_mock.get(f"{BASE_URL}/v1/token/info", status_code=status, json={"errors": []})++ result = validate_credentials("tok")++ assert result == (False, expected_message)++ def test_network_failure(self, requests_mock: Any) -> None:+ import requests as requests_lib++ requests_mock.get(f"{BASE_URL}/v1/token/info", exc=requests_lib.exceptions.ConnectionError)++ result = validate_credentials("tok")++ assert result == (False, "Could not reach Dovetail. Please check your network and try again.")+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("naive_datetime", datetime(2024, 1, 1, 12, 0, 0), "2024-01-01T12:00:00+00:00"),+ ("aware_datetime", datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC), "2024-01-01T12:00:00+00:00"),+ ("date_only", date(2024, 1, 1), "2024-01-01T00:00:00+00:00"),+ ("string_passthrough", "2024-01-01T00:00:00Z", "2024-01-01T00:00:00Z"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_incremental_value(value) == expected+++class TestGetResource:+ def test_full_refresh_endpoint_has_no_filter_param(self) -> None:+ resource = cast(+ dict[str, Any], get_resource("Projects", should_use_incremental_field=False, incremental_field=None)+ )++ assert resource["name"] == "Projects"+ assert resource["write_disposition"] == "replace"+ endpoint = resource["endpoint"]+ assert endpoint["path"] == "/v1/projects"+ assert endpoint["data_selector"] == "data"+ assert endpoint["params"] == {"page[limit]": 100, "sort": "created_at:asc"}+ assert endpoint["paginator"] == {+ "type": "cursor",+ "cursor_path": "page.next_cursor",+ "cursor_param": "page[start_cursor]",+ }+ assert resource["table_format"] == "delta"++ @parameterized.expand([("Tags",), ("Contacts",), ("Users",)])+ def test_other_full_refresh_endpoints_have_no_filter_param(self, endpoint_name: str) -> None:+ resource = cast(+ dict[str, Any], get_resource(endpoint_name, should_use_incremental_field=True, incremental_field=None)+ )+ # These endpoints have no incremental_fields declared, so requesting incremental sync+ # is a no-op: no filter param is added and the write disposition stays full replace.+ assert "filter[created_at][gte]" not in resource["endpoint"]["params"]+ assert resource["write_disposition"] == "replace"++ def test_incremental_endpoint_full_refresh_sends_null_filter(self) -> None:+ resource = cast(+ dict[str, Any], get_resource("Data", should_use_incremental_field=False, incremental_field=None)+ )++ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["params"]["filter[created_at][gte]"] is None++ def test_incremental_endpoint_incremental_sends_incremental_param(self) -> None:+ resource = cast(dict[str, Any], get_resource("Data", should_use_incremental_field=True, incremental_field=None))++ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ param = resource["endpoint"]["params"]["filter[created_at][gte]"]+ assert param["type"] == "incremental"+ assert param["cursor_path"] == "created_at"+ assert param["convert"] is _format_incremental_value++ def test_highlights_defaults_to_created_at_when_no_field_chosen(self) -> None:+ resource = cast(+ dict[str, Any], get_resource("Highlights", should_use_incremental_field=True, incremental_field=None)+ )+ assert "filter[created_at][gte]" in resource["endpoint"]["params"]+++class TestDovetailSourceTopLevel:+ def test_two_page_full_refresh_sync(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}/v1/projects",+ [+ {+ "json": {+ "data": [{"id": "p1", "title": "First"}],+ "page": {"total_count": 2, "has_more": True, "next_cursor": "CURSOR1"},+ }+ },+ {+ "json": {+ "data": [{"id": "p2", "title": "Second"}],+ "page": {"total_count": 2, "has_more": False, "next_cursor": None},+ }+ },+ ],+ )++ response = dovetail_source(+ api_key="tok",+ endpoint="Projects",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_FakeResumeManager(),+ )+ rows = _collect_rows(response)++ assert rows == [{"id": "p1", "title": "First"}, {"id": "p2", "title": "Second"}]+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_keys == ["created_at"]++ first_request, second_request = requests_mock.request_history+ assert first_request.qs["page[limit]"] == ["100"]+ assert "page[start_cursor]" not in first_request.qs+ # requests_mock's `.qs` lowercases query values.+ assert second_request.qs["page[start_cursor]"] == ["cursor1"]++ def test_incremental_sync_sends_filter(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}/v1/data",+ json={+ "data": [{"id": "d1", "created_at": "2024-01-02T00:00:00Z"}],+ "page": {"total_count": 1, "has_more": False, "next_cursor": None},+ },+ )++ response = dovetail_source(+ api_key="tok",+ endpoint="Data",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_FakeResumeManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="created_at",+ )+ rows = _collect_rows(response)++ assert rows == [{"id": "d1", "created_at": "2024-01-02T00:00:00Z"}]+ request = requests_mock.request_history[0]+ assert request.qs["filter[created_at][gte]"] == ["2024-01-01t00:00:00+00:00"]++ def test_resumes_from_saved_cursor(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}/v1/data",+ json={+ "data": [{"id": "d2"}],+ "page": {"total_count": 1, "has_more": False, "next_cursor": None},+ },+ )+ manager = _FakeResumeManager(state={"cursor": "SAVED_CURSOR"})++ response = dovetail_source(+ api_key="tok",+ endpoint="Data",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )+ _collect_rows(response)++ request = requests_mock.request_history[0]+ assert request.qs["page[start_cursor]"] == ["saved_cursor"]++ def test_saves_checkpoint_after_batch(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}/v1/data",+ json={+ "data": [{"id": "d1"}],+ "page": {"total_count": 2, "has_more": True, "next_cursor": "NEXT"},+ },+ )+ manager = _FakeResumeManager()++ response = dovetail_source(+ api_key="tok",+ endpoint="Data",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )+ # The checkpoint for a page is only saved once the generator resumes past its `yield`+ # (see rest_client.paginate), so fetch the first page and then advance once more to+ # observe the checkpoint saved right after it.+ items = response.items()+ assert isinstance(items, Iterable)+ iterator = iter(items)+ next(iterator)+ next(iterator)++ assert manager.saved == [{"cursor": "NEXT"}]+++class TestDovetailSourceFanout:+ def test_doc_comments_injects_parent_doc_id(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{BASE_URL}/v1/docs",+ json={+ "data": [{"id": "doc1"}, {"id": "doc2"}],+ "page": {"total_count": 2, "has_more": False, "next_cursor": None},+ },+ )+ requests_mock.get(+ f"{BASE_URL}/v1/docs/doc1/comments",+ json={+ "data": [{"id": "c1", "body": "hello"}],+ "page": {"total_count": 1, "has_more": False, "next_cursor": None},+ },+ )+ requests_mock.get(+ f"{BASE_URL}/v1/docs/doc2/comments",+ json={+ "data": [{"id": "c2", "body": "world"}],+ "page": {"total_count": 1, "has_more": False, "next_cursor": None},+ },+ )++ response = dovetail_source(+ api_key="tok",+ endpoint="DocComments",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_FakeResumeManager(),+ )+ rows = _collect_rows(response)++ assert rows == [+ {"id": "c1", "body": "hello", "doc_id": "doc1"},+ {"id": "c2", "body": "world", "doc_id": "doc2"},+ ]+ assert response.primary_keys == ["doc_id", "id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/tests/test_dovetail_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/tests/test_dovetail_source.pynew file mode 100644index 000000000000..cadf474f44ba--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dovetail/tests/test_dovetail_source.py@@ -0,0 +1,139 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.dovetail import DovetailResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.source import DovetailSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dovetail import (+ DovetailSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestDovetailSource:+ def setup_method(self) -> None:+ self.source = DovetailSource()+ self.team_id = 123+ self.config = DovetailSourceConfig(api_key="dovetail-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.DOVETAIL++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Dovetail"+ assert config.label == "Dovetail"+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # The source ships visible: unreleasedSource hides the connector from every user.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/dovetail.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/dovetail"++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_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_incremental_endpoints(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ for name in ("Data", "Docs", "Highlights"):+ assert schemas[name].supports_incremental is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["created_at"]++ for name in ("Projects", "Tags", "Contacts", "Users", "DocComments"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Data"])+ assert len(schemas) == 1+ assert schemas[0].name == "Data"++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://dovetail.com/api/v1/data",+ "403 Client Error: Forbidden for url: https://dovetail.com/api/v1/data",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient_failures(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in "500 Server Error for url: https://dovetail.com/api/v1/data" for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.source.validate_dovetail_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="Data")++ assert result == (True, None)+ mock_validate.assert_called_once_with("dovetail-key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DovetailResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.source.dovetail_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_dovetail_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Data"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"+ inputs.incremental_field = "created_at"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_dovetail_source.call_args.kwargs+ assert kwargs["api_key"] == "dovetail-key"+ assert kwargs["endpoint"] == "Data"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00Z"+ assert kwargs["incremental_field"] == "created_at"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.dovetail.source.dovetail_source")+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_dovetail_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Projects"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_dovetail_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dovetail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dovetail.pyindex 2117e233b916..148b6409ef0a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dovetail.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dovetail.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass DovetailSourceConfig(config.Config):- pass+ api_key: str