Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement coassemble import source (#69333)

Tom Owers4147f8fe8124
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 6cecbe657bd3..8a9c1db5df7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -97,6 +97,7 @@ the row lists both.
| chargify | HTTP | requests + `rest_source.RESTClient` | ✅ |
| checkout_com | HTTP | requests | ✅ |
| churnkey | HTTP | requests | ✅ |
+| coassemble | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
| codefresh | HTTP | requests | ✅ |
| coin_api | HTTP | requests | ✅ |
@@ -465,7 +466,6 @@ doesn't conflict with concurrent PRs.
- clarifai
- clazar
- cloudbeds
-- coassemble
- cockroachdb
- cody
- constant_contact
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/canonical_descriptions.py
new file mode 100644
index 000000000000..881612424d8d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/canonical_descriptions.py
@@ -0,0 +1,94 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Coassemble Headless API docs (https://developers.coassemble.com).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment. Coassemble timestamps
+# are ISO 8601 strings.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "courses": {
+ "description": "A course in the Coassemble workspace, including publish state and access settings.",
+ "docs_url": "https://developers.coassemble.com/api/courses",
+ "columns": {
+ "id": "The unique ID of the course.",
+ "active": "Whether the course is active.",
+ "title": "The course title.",
+ "description": "The course description.",
+ "image": "URL of the course image.",
+ "thumbnail": "URL of the course thumbnail.",
+ "start": "When access to the course opens, if scheduled.",
+ "finish": "When access to the course closes, if scheduled.",
+ "theme": "The theme applied to the course.",
+ "identified": "Whether learners must be identified to take the course.",
+ "private": "Whether the course is private.",
+ "paid": "Whether the course is paid.",
+ "price": "The course price, if paid.",
+ "key": "The shareable key for the course.",
+ "identifier": "The user identifier the course is scoped to, if any.",
+ "clientIdentifier": "The client identifier the course is scoped to, if any.",
+ "revision": "The current revision of the course.",
+ "published": "When the course was last published (ISO 8601).",
+ "translations": "Languages the course has been translated into.",
+ "created": "When the course was created (ISO 8601).",
+ "updated": "When the course was last updated (ISO 8601).",
+ "deleted": "When the course was deleted, if soft-deleted (ISO 8601).",
+ },
+ },
+ "collections": {
+ "description": "A collection — an ordered group of courses shared and tracked together.",
+ "docs_url": "https://developers.coassemble.com/api/collections",
+ "columns": {
+ "id": "The unique ID of the collection.",
+ "title": "The collection title.",
+ "description": "The collection description.",
+ "key": "The shareable key for the collection.",
+ "active": "Whether the collection is active.",
+ "identifier": "The user identifier the collection is scoped to, if any.",
+ "clientIdentifier": "The client identifier the collection is scoped to, if any.",
+ "created": "When the collection was created (ISO 8601).",
+ "updated": "When the collection was last updated (ISO 8601).",
+ "deleted": "When the collection was deleted, if soft-deleted (ISO 8601).",
+ },
+ },
+ "clients": {
+ "description": "A client — a grouping of users in a headless workspace, typically one of your customers or tenants.",
+ "docs_url": "https://developers.coassemble.com/api/identities",
+ "columns": {
+ "clientIdentifier": "The workspace-unique identifier of the client.",
+ "userCount": "The number of users belonging to the client.",
+ "created": "When the client was created (ISO 8601).",
+ "updated": "When the client was last updated (ISO 8601).",
+ },
+ },
+ "users": {
+ "description": "A user (learner) identity in the headless workspace.",
+ "docs_url": "https://developers.coassemble.com/api/identities",
+ "columns": {
+ "identifier": "The workspace-unique identifier of the user.",
+ "clientIdentifier": "The identifier of the client the user belongs to, if any.",
+ "name": "The user's display name.",
+ "avatar": "URL of the user's avatar.",
+ "testMode": "Whether the user is a test user whose activity is excluded from usage.",
+ "created": "When the user was created (ISO 8601).",
+ "updated": "When the user was last updated (ISO 8601).",
+ },
+ },
+ "course_trackings": {
+ "description": "A learner's progress record for a course (one row per learner per course attempt).",
+ "docs_url": "https://developers.coassemble.com/api/tracking",
+ "columns": {
+ "id": "The unique ID of the tracking record.",
+ "course_id": "The ID of the course the tracking belongs to (injected by PostHog; trackings are listed per course).",
+ "identifier": "The identifier of the user the tracking belongs to.",
+ "email": "The learner's email address, if captured.",
+ "commenced": "When the learner started the course (ISO 8601).",
+ "completed": "When the learner completed the course, if finished (ISO 8601).",
+ "passed": "Whether the learner passed the course.",
+ "progress_percent": "The learner's progress through the course, as a percentage.",
+ "total_time": "Total time the learner spent in the course.",
+ "feedback": "Feedback the learner left on the course.",
+ "language": "The language the learner took the course in.",
+ "scorm": "Whether the tracking came from a SCORM export.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/coassemble.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/coassemble.py
new file mode 100644
index 000000000000..9f179703a28d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/coassemble.py
@@ -0,0 +1,250 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.settings import COASSEMBLE_ENDPOINTS
+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.resumable import ResumableSourceManager
+
+# Single shared host — Coassemble has no per-workspace subdomains.
+COASSEMBLE_BASE_URL = "https://api.coassemble.com/api/v1/headless"
+# The documented default page size for every list endpoint. We request it explicitly so the
+# "short page means last page" termination check compares against the size the server enforces.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Hard cap on trackings pages per course (PAGE_SIZE * cap rows) so a paging bug on the vendor side
+# can never produce an unbounded scan of a single course.
+MAX_TRACKING_PAGES_PER_COURSE = 1_000
+# Cheap list probe used to confirm credentials are genuine. The workspace API key is
+# workspace-wide, so one probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/courses"
+
+
+class CoassembleRetryableError(Exception):
+ pass
+
+
+class CoassembleResumeConfig:
+ # Next page to fetch (0-indexed page-number pagination). Deterministic, so a crashed sync
+ # resumes from the page after the last one yielded; merge dedupes the re-pulled page on the
+ # primary key.
+ next_page: int = 0
+ # Trackings fan-out bookkeeping: courses fully paged through, and the course currently being
+ # paged (whose next page is `next_page`). Course ids rather than an index so a shifted course
+ # list between resume attempts can't skip a course.
+ completed_course_ids: list[int] = dataclasses.field(default_factory=list)
+ current_course_id: int | None = None
+
+
+def _headers(workspace_id: str, api_key: str) -> dict[str, str]:
+ # Vendor-specific scheme documented at https://developers.coassemble.com/get-started.
+ return {
+ "Authorization": f"COASSEMBLE:{workspace_id}:{api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _extract_items(data: Any, path: str) -> list[dict[str, Any]]:
+ # List endpoints document a plain JSON array; accept common object wrappers defensively since
+ # not every endpoint's response envelope is shown in the docs.
+ if isinstance(data, list):
+ return data
+ if isinstance(data, dict):
+ for key in ("data", "results", "items"):
+ if isinstance(data.get(key), list):
+ return data[key]
+ raise CoassembleRetryableError(f"Coassemble returned an unexpected payload for {path}: {type(data).__name__}")
+
+
+@retry(
+ retry=retry_if_exception_type((CoassembleRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ page: int,
+ logger: FilteringBoundLogger,
+ extra_params: dict[str, Any] | None = None,
+) -> list[dict[str, Any]]:
+ params: dict[str, Any] = {"page": page, "length": PAGE_SIZE, **(extra_params or {})}
+
+ response = session.get(f"{COASSEMBLE_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CoassembleRetryableError(f"Coassemble API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Coassemble API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ return _extract_items(response.json(), path)
+
+
+def _iter_pages(
+ session: requests.Session,
+ path: str,
+ logger: FilteringBoundLogger,
+ start_page: int = 0,
+ extra_params: dict[str, Any] | None = None,
+) -> Iterator[tuple[int, list[dict[str, Any]]]]:
+ """Yield ``(page_number, items)`` from ``start_page`` until a short or empty page."""
+ page = start_page
+ while True:
+ items = _fetch_page(session, path, page, logger, extra_params=extra_params)
+ if items:
+ yield page, items
+
+ # A short page marks the end of the collection (we always request PAGE_SIZE).
+ if len(items) < PAGE_SIZE:
+ break
+
+ page += 1
+
+
+def _list_course_ids(session: requests.Session, logger: FilteringBoundLogger) -> list[int]:
+ course_ids: list[int] = []
+ for _, courses in _iter_pages(session, COASSEMBLE_ENDPOINTS["courses"].path, logger):
+ course_ids.extend(course["id"] for course in courses)
+ return course_ids
+
+
+def get_rows(
+ workspace_id: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoassembleResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = COASSEMBLE_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(workspace_id, api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.fan_out_by_course:
+ yield from _get_tracking_rows(session, logger, resumable_source_manager, resume)
+ return
+
+ page = resume.next_page if resume else 0
+ if resume and resume.next_page > 0:
+ logger.debug(f"Coassemble: resuming {endpoint} from page {page}")
+
+ for fetched_page, items in _iter_pages(session, config.path, logger, start_page=page):
+ yield items
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(CoassembleResumeConfig(next_page=fetched_page + 1))
+
+
+def _get_tracking_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoassembleResumeConfig],
+ resume: CoassembleResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ path = COASSEMBLE_ENDPOINTS["course_trackings"].path
+ completed_course_ids = list(resume.completed_course_ids) if resume else []
+ completed_set = set(completed_course_ids)
+
+ for course_id in _list_course_ids(session, logger):
+ if course_id in completed_set:
+ continue
+
+ start_page = resume.next_page if resume and resume.current_course_id == course_id else 0
+ last_page_fetched: int | None = None
+
+ for page, items in _iter_pages(session, path, logger, start_page=start_page, extra_params={"id": course_id}):
+ for item in items:
+ # Tracking rows don't reference their course, so inject it (also part of the
+ # primary key — see settings.py).
+ item["course_id"] = course_id
+ yield items
+ last_page_fetched = page
+ resumable_source_manager.save_state(
+ CoassembleResumeConfig(
+ next_page=page + 1,
+ completed_course_ids=completed_course_ids,
+ current_course_id=course_id,
+ )
+ )
+
+ if page - start_page + 1 >= MAX_TRACKING_PAGES_PER_COURSE:
+ logger.warning(
+ f"Coassemble: hit trackings page cap ({MAX_TRACKING_PAGES_PER_COURSE}) for course {course_id}; "
+ "remaining trackings for this course are skipped this sync"
+ )
+ break
+
+ completed_course_ids.append(course_id)
+ completed_set.add(course_id)
+ resumable_source_manager.save_state(
+ CoassembleResumeConfig(
+ next_page=0,
+ completed_course_ids=completed_course_ids,
+ current_course_id=None,
+ )
+ )
+ if last_page_fetched is not None:
+ logger.debug(f"Coassemble: finished trackings for course {course_id}")
+
+
+def coassemble_source(
+ workspace_id: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoassembleResumeConfig],
+) -> SourceResponse:
+ config = COASSEMBLE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ workspace_id=workspace_id,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(workspace_id: str, api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the workspace credentials.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(workspace_id, api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{COASSEMBLE_BASE_URL}{path}", params={"page": 0, "length": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Coassemble: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Coassemble returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(workspace_id: str, api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(workspace_id, api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Coassemble workspace ID or API key"
+ return False, message or "Could not validate Coassemble credentials"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/settings.py
new file mode 100644
index 000000000000..115fffcc8676
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/settings.py
@@ -0,0 +1,40 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class CoassembleEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Trackings can only be listed per course (`id` is a required query param), so the endpoint
+ # fans out over the workspace's courses.
+ fan_out_by_course: bool = False
+
+
+# Coassemble Headless API list endpoints (https://developers.coassemble.com). All are full refresh
+# only: the courses/collections/clients/users lists expose no server-side timestamp filter, and the
+# trackings `start`/`end` params filter on mutable progress timestamps (`commenced`/`completed`)
+# that we could not smoke-test against a live workspace, so we conservatively re-pull and let merge
+# dedupe on the primary key.
+COASSEMBLE_ENDPOINTS: dict[str, CoassembleEndpointConfig] = {
+ "courses": CoassembleEndpointConfig(name="courses", path="/courses"),
+ "collections": CoassembleEndpointConfig(name="collections", path="/collections"),
+ # Client objects carry no numeric `id`; `clientIdentifier` is the workspace-unique handle used
+ # by every other endpoint to reference them.
+ "clients": CoassembleEndpointConfig(name="clients", path="/clients", primary_keys=["clientIdentifier"]),
+ # Users are addressable by bare `identifier` (`GET /user/{identifier}`), so it is
+ # workspace-unique on its own.
+ "users": CoassembleEndpointConfig(name="users", path="/users", primary_keys=["identifier"]),
+ # Tracking rows don't include the course they belong to, so the transport injects `course_id`;
+ # it is part of the key because tracking `id` uniqueness across courses is undocumented.
+ "course_trackings": CoassembleEndpointConfig(
+ name="course_trackings",
+ path="/trackings",
+ primary_keys=["course_id", "id"],
+ fan_out_by_course=True,
+ ),
+}
+
+ENDPOINTS = tuple(COASSEMBLE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/source.py
index 7bf0f2052b8d..fa50844fffc0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from 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.coassemble.coassemble import (
+ CoassembleResumeConfig,
+ coassemble_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.settings import (
+ COASSEMBLE_ENDPOINTS,
+ ENDPOINTS,
+)
+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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CoassembleSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CoassembleSource(SimpleSource[CoassembleSourceConfig]):
+class CoassembleSource(ResumableSource[CoassembleSourceConfig, CoassembleResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.COASSEMBLE
@@ -24,7 +47,96 @@ class CoassembleSource(SimpleSource[CoassembleSourceConfig]):
name=SchemaExternalDataSourceType.COASSEMBLE,
category=DataWarehouseSourceCategory.HR___RECRUITING,
label="Coassemble",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["lms", "training", "courses"],
+ caption="""Enter your Coassemble workspace ID and API key to pull your courses, collections, learners, and learner progress into the PostHog Data warehouse.
+
+You can generate an API key from your workspace API settings in [Coassemble](https://coassemble.com). API access must be enabled on your workspace plan.
+""",
iconPath="/static/services/coassemble.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/coassemble",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="workspace_id",
+ label="Workspace ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.coassemble.com": "Your Coassemble workspace ID or API key is invalid or has been regenerated. Generate a new key in your workspace API settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.coassemble.com": "Your Coassemble API key does not have access to this data. Check that API access is enabled on your workspace plan, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CoassembleSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — see the rationale in settings.py.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: CoassembleSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is workspace-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.workspace_id, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CoassembleResumeConfig]:
+ return ResumableSourceManager[CoassembleResumeConfig](inputs, CoassembleResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CoassembleSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CoassembleResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in COASSEMBLE_ENDPOINTS:
+ raise ValueError(f"Unknown Coassemble schema '{inputs.schema_name}'")
+
+ return coassemble_source(
+ workspace_id=config.workspace_id,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/tests/test_coassemble.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/tests/test_coassemble.py
new file mode 100644
index 000000000000..7727158f1cc7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/tests/test_coassemble.py
@@ -0,0 +1,315 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble import coassemble
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.coassemble import (
+ COASSEMBLE_BASE_URL,
+ PAGE_SIZE,
+ CoassembleResumeConfig,
+ CoassembleRetryableError,
+ _headers,
+ check_access,
+ coassemble_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.settings import (
+ COASSEMBLE_ENDPOINTS,
+ ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = coassemble._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: CoassembleResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[CoassembleResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> CoassembleResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: CoassembleResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(prefix: str, start: int, count: int) -> list[dict[str, Any]]:
+ return [{"id": f"{prefix}-{i}"} for i in range(start, start + count)]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[tuple[str, int], list[dict]],
+ endpoint: str = "courses",
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, page: int, logger: Any, extra_params: Any = None) -> list[dict]:
+ return pages.get((path, page), [])
+
+ monkeypatch.setattr(coassemble, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(coassemble, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ workspace_id="ws-1",
+ api_key="sk-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_short_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {("/courses", 0): _page("c", 0, 2)})
+ assert rows == _page("c", 0, 2)
+ # A short first page ends the sync; state is still saved after the yield so a crash
+ # mid-persist re-fetches only the final page.
+ assert [s.next_page for s in manager.saved] == [1]
+
+ def test_full_page_advances_until_short_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {("/courses", 0): _page("c", 0, PAGE_SIZE), ("/courses", 1): _page("c", PAGE_SIZE, 3)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == PAGE_SIZE + 3
+ assert [s.next_page for s in manager.saved] == [1, 2]
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(CoassembleResumeConfig(next_page=2))
+ # Pages 0 and 1 must never be fetched on resume; the pages dict only knows page 2.
+ rows = self._collect(manager, monkeypatch, {("/courses", 2): _page("c", 0, 1)})
+ assert rows == _page("c", 0, 1)
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {})
+ assert rows == []
+ assert manager.saved == []
+
+
+class TestTrackingFanOut:
+ @staticmethod
+ def _run(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ courses: list[dict],
+ trackings: dict[tuple[int, int], list[dict]],
+ ) -> tuple[list[dict], list[dict[str, Any]]]:
+ calls: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, path: str, page: int, logger: Any, extra_params: Any = None) -> list[dict]:
+ calls.append({"path": path, "page": page, "extra_params": extra_params})
+ if path == "/courses":
+ return courses if page == 0 else []
+ assert extra_params is not None
+ return trackings.get((extra_params["id"], page), [])
+
+ monkeypatch.setattr(coassemble, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(coassemble, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ workspace_id="ws-1",
+ api_key="sk-key",
+ endpoint="course_trackings",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows, calls
+
+ def test_iterates_courses_and_injects_course_id(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ courses = [{"id": 11}, {"id": 22}]
+ trackings = {(11, 0): [{"id": 1}, {"id": 2}], (22, 0): [{"id": 3}]}
+ rows, _ = self._run(manager, monkeypatch, courses, trackings)
+ assert rows == [
+ {"id": 1, "course_id": 11},
+ {"id": 2, "course_id": 11},
+ {"id": 3, "course_id": 22},
+ ]
+ # Each course is marked completed after its pages are exhausted.
+ assert manager.saved[-1].completed_course_ids == [11, 22]
+ assert manager.saved[-1].current_course_id is None
+
+ def test_resume_skips_completed_courses_and_starts_at_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(
+ CoassembleResumeConfig(next_page=1, completed_course_ids=[11], current_course_id=22)
+ )
+ courses = [{"id": 11}, {"id": 22}]
+ # Only page 1 of course 22 exists in the fixture: fetching course 11 or page 0 of course 22
+ # would yield rows that then fail the assertion below.
+ trackings = {(22, 1): [{"id": 9}]}
+ rows, calls = self._run(manager, monkeypatch, courses, trackings)
+ assert rows == [{"id": 9, "course_id": 22}]
+ tracking_calls = [c for c in calls if c["path"] == "/trackings"]
+ assert all(c["extra_params"]["id"] == 22 for c in tracking_calls)
+ assert tracking_calls[0]["page"] == 1
+
+ def test_state_saved_after_each_trackings_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ courses = [{"id": 11}]
+ trackings = {
+ (11, 0): [{"id": i} for i in range(PAGE_SIZE)],
+ (11, 1): [{"id": PAGE_SIZE}],
+ }
+ self._run(manager, monkeypatch, courses, trackings)
+ # Two in-course saves (after each yielded page) then the completion save.
+ assert [(s.current_course_id, s.next_page) for s in manager.saved] == [(11, 1), (11, 2), (None, 0)]
+
+ def test_page_cap_stops_runaway_course(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(coassemble, "MAX_TRACKING_PAGES_PER_COURSE", 2)
+ manager = _FakeResumableManager()
+ courses = [{"id": 11}]
+ # Every page is full, so without the cap this would loop past page 2.
+ trackings = {(11, page): [{"id": page}] * PAGE_SIZE for page in range(10)}
+ rows, calls = self._run(manager, monkeypatch, courses, trackings)
+ assert len(rows) == 2 * PAGE_SIZE
+ assert len([c for c in calls if c["path"] == "/trackings"]) == 2
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else []
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(CoassembleRetryableError):
+ _fetch_page_unwrapped(session, "/courses", 0, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/courses", 0, MagicMock())
+
+ @parameterized.expand(
+ [
+ ("plain_array", [{"id": 1}]),
+ ("data_wrapper", {"data": [{"id": 1}]}),
+ ("results_wrapper", {"results": [{"id": 1}]}),
+ ]
+ )
+ def test_accepts_documented_and_wrapped_payloads(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ assert _fetch_page_unwrapped(session, "/courses", 0, MagicMock()) == [{"id": 1}]
+
+ @parameterized.expand([("string", "nope"), ("object_without_list", {"count": 1})])
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(CoassembleRetryableError):
+ _fetch_page_unwrapped(session, "/courses", 0, MagicMock())
+
+ def test_request_carries_pagination_and_extra_params(self) -> None:
+ session = self._session_returning(200, [])
+ _fetch_page_unwrapped(session, "/trackings", 3, MagicMock(), extra_params={"id": 42})
+ args, kwargs = session.get.call_args
+ assert args[0] == f"{COASSEMBLE_BASE_URL}/trackings"
+ assert kwargs["params"] == {"page": 3, "length": PAGE_SIZE, "id": 42}
+
+
+class TestAuthHeaders:
+ def test_uses_vendor_specific_authorization_scheme(self) -> None:
+ # Coassemble rejects standard schemes (Bearer etc.) with "Invalid Authorization header";
+ # the documented format is COASSEMBLE:<workspace_id>:<api_key>.
+ assert _headers("ws-1", "sk-key")["Authorization"] == "COASSEMBLE:ws-1:sk-key"
+
+
+class TestCheckAccess:
+ def _session(self, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Coassemble returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with patch.object(coassemble, "make_tracked_session", return_value=self._session(response)):
+ assert check_access("ws-1", "sk-key") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ session = self._session(requests.ConnectionError("boom"))
+ with patch.object(coassemble, "make_tracked_session", return_value=session):
+ status, message = check_access("ws-1", "sk-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Coassemble workspace ID or API key"),
+ ("forbidden", 403, False, "Invalid Coassemble workspace ID or API key"),
+ ("server_error", 500, False, "Coassemble returned HTTP 500"),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ with patch.object(coassemble, "make_tracked_session", return_value=self._session(response)):
+ assert validate_credentials("ws-1", "sk-key") == (expected_valid, expected_message)
+
+
+class TestCoassembleSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = coassemble_source(
+ workspace_id="ws-1",
+ api_key="sk-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == COASSEMBLE_ENDPOINTS[endpoint].primary_keys
+ # Trackings/courses only guarantee mutable progress timestamps, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_trackings_key_includes_injected_course_id(self) -> None:
+ # Tracking rows are aggregated across every course; without the parent id in the key,
+ # per-course id collisions would seed duplicate rows that every later merge multi-matches.
+ assert COASSEMBLE_ENDPOINTS["course_trackings"].primary_keys == ["course_id", "id"]
+
+ def test_clients_and_users_use_identifier_keys(self) -> None:
+ # Neither object carries a numeric `id` in the API response.
+ assert COASSEMBLE_ENDPOINTS["clients"].primary_keys == ["clientIdentifier"]
+ assert COASSEMBLE_ENDPOINTS["users"].primary_keys == ["identifier"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/tests/test_coassemble_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/tests/test_coassemble_source.py
new file mode 100644
index 000000000000..b1a9bc3ab519
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/tests/test_coassemble_source.py
@@ -0,0 +1,128 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.coassemble import (
+ CoassembleResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.source import CoassembleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CoassembleSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestCoassembleSource:
+ def setup_method(self) -> None:
+ self.source = CoassembleSource()
+ self.team_id = 123
+ self.config = CoassembleSourceConfig(workspace_id="ws-1", api_key="sk-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.COASSEMBLE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Coassemble"
+ assert config.label == "Coassemble"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Deliberately still hidden — the source lands unreleased until it has been verified
+ # against a live workspace.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/coassemble"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["workspace_id", "api_key"]
+
+ 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_no_connection_host_fields(self) -> None:
+ # The base URL is hardcoded and workspace_id only selects the tenant on Coassemble's own
+ # host, so there is no non-secret field an editor could retarget to exfiltrate the key.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["courses"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "courses"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.coassemble.com/api/v1/headless/courses",),
+ ("403 Client Error: Forbidden for url: https://api.coassemble.com/api/v1/headless/trackings",),
+ ]
+ )
+ 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)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.coassemble.com/api/v1/headless/courses",),
+ ("429 Client Error: Too Many Requests for url: https://api.coassemble.com/api/v1/headless/users",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.source.validate_credentials"
+ )
+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (False, "Invalid Coassemble workspace ID or API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ assert result == (False, "Invalid Coassemble workspace ID or API key")
+ mock_validate.assert_called_once_with("ws-1", "sk-key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CoassembleResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.source.coassemble_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "courses"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["workspace_id"] == "ws-1"
+ assert kwargs["api_key"] == "sk-key"
+ assert kwargs["endpoint"] == "courses"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Coassemble schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index b9d58ff25e68..80e216ef484a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -789,7 +789,8 @@ class CloudflareSourceConfig(config.Config):
@config.config
class CoassembleSourceConfig(config.Config):
- pass
+ workspace_id: str
+ api_key: str
@config.config