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(warehouse-sources): add coassemble tracking and usage tables (#103351)

Tom Owers42a2ba430ce0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index c04db356476e..9f114ff8156e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1690,17 +1690,17 @@ Note: The ReadMe reference page embeds the full sidebar, which enumerates the v2
## Coassemble — gaps
-Today (5): `clients`, `collections`, `course_trackings`, `courses`, `users`
+Today (10): `client_allowances`, `client_usage`, `clients`, `collection_trackings`, `collections`, `course_trackings`, `courses`, `screen_trackings`, `user_trackings`, `users`
Diffed against: <https://developers.coassemble.com/api/tracking>
-- [ ] `/collection/trackings` — Learner progress at the collection (learning path) level - the collections table is synced today with no progress data against it (high)
-- [ ] `/screen/trackings` — Per-screen progress, the finest analytical grain; the only way to see where inside a course learners drop off (high)
-- [ ] `/user/trackings` — Progress rows keyed by learner across all courses, the natural per-user completion table (medium)
-- [ ] `/usage/clients (and /usage/client/{identifier})` — Per-client consumption (identified/anonymous recipients, narration tokens, image generations) - joins to the clients table already synced (medium)
+- [x] `/collection/trackings` — Learner progress at the collection (learning path) level - the collections table is synced today with no progress data against it (high)
+- [x] `/screen/trackings` — Per-screen progress, the finest analytical grain; the only way to see where inside a course learners drop off (high)
+- [x] `/user/trackings` — Progress rows keyed by learner across all courses, the natural per-user completion table (medium)
+- [x] `/usage/clients (and /usage/client/{identifier})` — Per-client consumption (identified/anonymous recipients, narration tokens, image generations) - joins to the clients table already synced (medium)
- [ ] `/usage/allowances` — Workspace billing-period limits and current usage, giving usage rows a denominator (low)
-Note: Headless API (https://api.coassemble.com/api/v1/headless). Docs sections are Courses, Generate, Collections, Identities, Tracking, Themes, Translations, Usage, Webhooks. The synced course_trackings maps to GET /trackings; the tracking section documents three sibling grains that are not synced. Themes/Translations are content config and excluded.
+Note: Headless API (https://api.coassemble.com/api/v1/headless). Docs sections are Courses, Generate, Collections, Identities, Tracking, Themes, Translations, Usage, Webhooks. The synced course_trackings maps to GET /trackings; its three sibling grains (collection, screen and user trackings) are synced alongside it. Themes/Translations are content config and excluded.
## Coda — gaps
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
index 881612424d8d..ba9a7278cfe9 100644
--- 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
@@ -91,4 +91,86 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"scorm": "Whether the tracking came from a SCORM export.",
},
},
+ "screen_trackings": {
+ "description": "A learner's screen-level progress through a course (one row per learner per course), with each screen attempt and its per-question progress nested under `attempts`.",
+ "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; screen trackings are listed per course).",
+ "identifier": "The identifier of the user the tracking belongs to.",
+ "clientIdentifier": "The identifier of the client the user belongs to, if any.",
+ "name": "The learner's display name.",
+ "avatar": "URL of the learner's avatar.",
+ "language": "The language the learner took the course in.",
+ "commenced": "When the learner started the course (ISO 8601).",
+ "completed": "When the learner completed the course, if finished (ISO 8601).",
+ "progressPercent": "The learner's progress through the course, as a percentage.",
+ "attempts": "The learner's screen attempts, each with its score, timings and per-question progress.",
+ },
+ },
+ "collection_trackings": {
+ "description": "A learner's progress record for a collection (learning path), with the per-course breakdown nested under `courses`.",
+ "docs_url": "https://developers.coassemble.com/api/tracking",
+ "columns": {
+ "id": "The unique ID of the collection tracking record.",
+ "collection_id": "The ID of the collection the tracking belongs to (injected by PostHog; collection trackings are listed per collection).",
+ "identifier": "The identifier of the user the tracking belongs to.",
+ "name": "The learner's display name.",
+ "commenced": "When the learner started the collection (ISO 8601).",
+ "completed": "When the learner completed the collection, if finished (ISO 8601).",
+ "progressPercent": "The learner's progress through the collection, as a percentage.",
+ "totalTime": "Total time the learner spent in the collection.",
+ "courses": "Per-course progress within the collection, in sequence order.",
+ },
+ },
+ "user_trackings": {
+ "description": "A learner's progress record for a course, keyed by learner rather than by course (one row per course the learner has taken).",
+ "docs_url": "https://developers.coassemble.com/api/tracking",
+ "columns": {
+ "id": "The unique ID of the tracking record.",
+ "user_identifier": "The identifier of the learner the trackings were listed for (injected by PostHog).",
+ "identifier": "The identifier of the user the tracking belongs to.",
+ "clientIdentifier": "The identifier of the client the user belongs to, if any.",
+ "courseId": "The ID of the course the tracking belongs to.",
+ "collectionTrackingId": "The collection tracking this course tracking rolls up into, if the course was taken as part of a collection.",
+ "email": "The learner's email address, if captured.",
+ "name": "The learner's display name.",
+ "commenced": "When the learner started the course (ISO 8601).",
+ "completed": "When the learner completed the course, if finished (ISO 8601).",
+ "totalTime": "Total time the learner spent in the course.",
+ "scorePercent": "The learner's score, as a percentage.",
+ "progressPercent": "The learner's progress through the course, as a percentage.",
+ "feedback": "Feedback the learner left on the course.",
+ "language": "The language the learner took the course in.",
+ "referrer": "Where the learner came from.",
+ "attempts": "The learner's screen attempts for this course.",
+ "created": "When the tracking was created (ISO 8601).",
+ "updated": "When the tracking was last updated (ISO 8601).",
+ "deleted": "When the tracking was deleted, if soft-deleted (ISO 8601).",
+ },
+ },
+ "client_usage": {
+ "description": "Consumption for a client in the current billing period, one row per usage metric.",
+ "docs_url": "https://developers.coassemble.com/api/usage",
+ "columns": {
+ "clientIdentifier": "The identifier of the client the usage belongs to.",
+ "metric": "The usage metric — identified recipients, anonymous recipients, narration tokens or image generations.",
+ "currentUsage": "How much of the metric the client has consumed in the period.",
+ "periodStart": "When the billing period started (ISO 8601).",
+ "periodEnd": "When the billing period ends (ISO 8601).",
+ },
+ },
+ "client_allowances": {
+ "description": "The monthly allowance behind a client's usage, one row per usage metric — the denominator for client_usage.",
+ "docs_url": "https://developers.coassemble.com/api/usage",
+ "columns": {
+ "clientIdentifier": "The identifier of the client the allowance belongs to (injected by PostHog; allowances are read one client at a time).",
+ "metric": "The usage metric the allowance applies to.",
+ "limit": "The monthly cap for the metric; unset means unlimited.",
+ "topUp": "Extra allowance added on top of the cap for the period.",
+ "currentUsage": "How much of the metric the client has consumed in the period.",
+ "periodStart": "When the billing period started (ISO 8601).",
+ "periodEnd": "When the billing period ends (ISO 8601).",
+ },
+ },
}
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
index e7d72b852595..4ee49e9edc0b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/coassemble.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/coassemble.py
@@ -1,21 +1,35 @@
import logging
import dataclasses
+from collections.abc import Callable
from typing import Any, Optional
from requests import Response
-from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.settings import COASSEMBLE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.settings import (
+ COASSEMBLE_ENDPOINTS,
+ PAGE_SIZE,
+ CoassembleEndpointConfig,
+)
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,
rest_api_resources,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ make_parent_key_name,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
PageNumberPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
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.common.typings import SourceResponse
@@ -24,23 +38,18 @@ logger = logging.getLogger(__name__)
# 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
-# 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
+# Hard cap on child pages per fan-out parent (page_size * cap rows) so a paging bug on the vendor
+# side can never produce an unbounded scan of a single parent.
+MAX_FAN_OUT_PAGES_PER_PARENT = 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"
-# Trackings can only be listed per course: `id` is a required QUERY param. The framework binds
-# resolve params via path templating, so the query string rides in the path (requests merges the
-# remaining params into it).
-TRACKINGS_CHILD_PATH = f"{COASSEMBLE_ENDPOINTS['course_trackings'].path}?id={{id}}"
+# The only endpoint that can carry a bookmark saved before the fan-out moved onto the framework.
+LEGACY_FAN_OUT_ENDPOINT = "course_trackings"
[email protected](frozen=True)
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
@@ -50,16 +59,17 @@ class CoassembleResumeConfig:
# still parses (and is translated into fanout_state on load); no longer written.
completed_course_ids: list[int] = dataclasses.field(default_factory=list)
current_course_id: int | None = None
- # Framework fan-out resume state for the course_trackings endpoint:
+ # Framework fan-out resume state for a fan-out endpoint:
# {"completed": [child_path, ...], "current": child_path | None, "child_state": {...} | None}.
fanout_state: dict | None = None
class CoassemblePageNumberPaginator(PageNumberPaginator):
"""0-indexed page-number pagination where every list endpoint serves fixed-length pages, so a
- short page marks the end of the collection (we always request PAGE_SIZE — no extra empty-page
- request). ``max_pages`` caps how many pages one paginate call fetches (the runaway-course guard
- for trackings); the paginator is deep-copied per fan-out parent, so the cap is per course.
+ short page marks the end of the collection (we always request the endpoint's page size — no
+ extra empty-page request). ``max_pages`` caps how many pages one paginate call fetches (the
+ runaway-parent guard for fan-outs); the paginator is deep-copied per fan-out parent, so the cap
+ is per parent.
"""
def __init__(self, page_size: int = PAGE_SIZE, max_pages: Optional[int] = None) -> None:
@@ -75,7 +85,7 @@ class CoassemblePageNumberPaginator(PageNumberPaginator):
self._has_next_page = False
if self.max_pages is not None and self._pages_fetched >= self.max_pages and self._has_next_page:
logger.warning(
- "Coassemble: hit trackings page cap (%s); remaining rows for this parent are skipped this sync",
+ "Coassemble: hit fan-out page cap (%s); remaining rows for this parent are skipped this sync",
self.max_pages,
)
self._has_next_page = False
@@ -102,32 +112,34 @@ def _client_config(workspace_id: str, api_key: str) -> ClientConfig:
}
+def _paginator(config: CoassembleEndpointConfig, max_pages: Optional[int] = None) -> BasePaginator:
+ if config.page_size is None:
+ return SinglePagePaginator()
+ return CoassemblePageNumberPaginator(page_size=config.page_size, max_pages=max_pages)
+
+
+def _endpoint_resource(config: CoassembleEndpointConfig, max_pages: Optional[int] = None) -> EndpointResource:
+ # Endpoints document a JSON array (or, where `data_selector` is set, an array under one
+ # envelope key); a 200 body of any other shape means the response shape changed — fail loud
+ # instead of silently syncing 0 rows.
+ endpoint: Endpoint = {
+ "path": config.path,
+ "params": {"length": config.page_size} if config.page_size is not None else {},
+ "paginator": _paginator(config, max_pages),
+ "data_selector": config.data_selector,
+ "data_selector_required": True,
+ }
+ return {"name": config.name, "endpoint": endpoint}
+
+
def _standard_resource(
- workspace_id: str,
- api_key: str,
- endpoint: str,
+ client_config: ClientConfig,
+ config: CoassembleEndpointConfig,
team_id: int,
job_id: str,
manager: ResumableSourceManager[CoassembleResumeConfig],
) -> Resource:
- config = COASSEMBLE_ENDPOINTS[endpoint]
-
- # List endpoints document a plain JSON array; a 200 body of any other shape means the response
- # shape changed — fail loud instead of silently syncing 0 rows.
- rest_config: RESTAPIConfig = {
- "client": _client_config(workspace_id, api_key),
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": {"length": PAGE_SIZE},
- "paginator": CoassemblePageNumberPaginator(),
- "data_selector_required": True,
- },
- }
- ],
- }
+ rest_config: RESTAPIConfig = {"client": client_config, "resources": [_endpoint_resource(config)]}
initial_paginator_state: Optional[dict[str, Any]] = None
if manager.can_resume():
@@ -151,17 +163,20 @@ def _standard_resource(
)
-def _tracking_child_path(course_id: int) -> str:
- return TRACKINGS_CHILD_PATH.format(id=course_id)
+def _stamp_parent_value(parent_name: str, parent_field: str, column: str) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ injected_key = make_parent_key_name(parent_name, parent_field)
+ def stamp(row: dict[str, Any]) -> dict[str, Any]:
+ value = row.pop(injected_key, None)
+ if value is not None:
+ row[column] = value
+ return row
-def _stamp_course_id(row: dict[str, Any]) -> dict[str, Any]:
- # include_from_parent lands the parent course id as `_courses_id`; rename it to the plain
- # `course_id` column tracking rows carry (also part of the primary key — see settings.py).
- value = row.pop("_courses_id", None)
- if value is not None:
- row["course_id"] = value
- return row
+ return stamp
+
+
+def _legacy_child_path(course_id: int) -> str:
+ return COASSEMBLE_ENDPOINTS[LEGACY_FAN_OUT_ENDPOINT].path.format(id=course_id)
def _translate_legacy_fanout_state(resume: CoassembleResumeConfig) -> Optional[dict[str, Any]]:
@@ -173,66 +188,60 @@ def _translate_legacy_fanout_state(resume: CoassembleResumeConfig) -> Optional[d
"""
if not resume.completed_course_ids and resume.current_course_id is None:
return None
- current = _tracking_child_path(resume.current_course_id) if resume.current_course_id is not None else None
+ current = _legacy_child_path(resume.current_course_id) if resume.current_course_id is not None else None
return {
- "completed": [_tracking_child_path(course_id) for course_id in resume.completed_course_ids],
+ "completed": [_legacy_child_path(course_id) for course_id in resume.completed_course_ids],
"current": current,
"child_state": {"page": resume.next_page} if current is not None else None,
}
-def _trackings_resource(
- workspace_id: str,
- api_key: str,
+def _initial_fan_out_state(
+ config: CoassembleEndpointConfig, manager: ResumableSourceManager[CoassembleResumeConfig]
+) -> Optional[dict[str, Any]]:
+ if not manager.can_resume():
+ return None
+ resume = manager.load_state()
+ if resume is None:
+ return None
+ if resume.fanout_state is not None:
+ return resume.fanout_state
+ if config.name != LEGACY_FAN_OUT_ENDPOINT:
+ return None
+ return _translate_legacy_fanout_state(resume)
+
+
+def _fan_out_resource(
+ client_config: ClientConfig,
+ config: CoassembleEndpointConfig,
team_id: int,
job_id: str,
manager: ResumableSourceManager[CoassembleResumeConfig],
) -> Resource:
- """Fan out over every course, listing its trackings and stamping the parent `course_id`.
+ """Fan out over a parent endpoint, listing the child rows per parent and stamping the parent
+ reference onto each row.
- /trackings requires an `id` (the course id), so trackings can only be pulled per course. Full
- refresh — re-pulled rows on resume are deduped by the (course_id, id) primary key on merge.
+ Full refresh — re-pulled rows on resume are deduped by the endpoint's primary key on merge.
"""
- courses_config = COASSEMBLE_ENDPOINTS["courses"]
+ fan_out = config.fan_out
+ assert fan_out is not None
+ parent_config = COASSEMBLE_ENDPOINTS[fan_out.parent]
+
+ child = _endpoint_resource(config, max_pages=MAX_FAN_OUT_PAGES_PER_PARENT)
+ child_endpoint = child["endpoint"]
+ assert isinstance(child_endpoint, dict)
+ child_endpoint["params"] = {
+ **(child_endpoint.get("params") or {}),
+ fan_out.param: {"type": "resolve", "resource": parent_config.name, "field": fan_out.resolve_field},
+ }
+ child["include_from_parent"] = [fan_out.resolve_field]
+ child["data_map"] = _stamp_parent_value(parent_config.name, fan_out.resolve_field, fan_out.stamp_column)
rest_config: RESTAPIConfig = {
- "client": _client_config(workspace_id, api_key),
- "resources": [
- {
- "name": "courses",
- "endpoint": {
- "path": courses_config.path,
- "params": {"length": PAGE_SIZE},
- "paginator": CoassemblePageNumberPaginator(),
- "data_selector_required": True,
- },
- },
- {
- "name": "course_trackings",
- "endpoint": {
- "path": TRACKINGS_CHILD_PATH,
- "params": {
- "id": {"type": "resolve", "resource": "courses", "field": "id"},
- "length": PAGE_SIZE,
- },
- "paginator": CoassemblePageNumberPaginator(max_pages=MAX_TRACKING_PAGES_PER_COURSE),
- "data_selector_required": True,
- },
- "include_from_parent": ["id"],
- "data_map": _stamp_course_id,
- },
- ],
+ "client": client_config,
+ "resources": [_endpoint_resource(parent_config), child],
}
- initial_paginator_state: Optional[dict[str, Any]] = None
- if manager.can_resume():
- resume = manager.load_state()
- if resume is not None:
- if resume.fanout_state is not None:
- initial_paginator_state = resume.fanout_state
- else:
- initial_paginator_state = _translate_legacy_fanout_state(resume)
-
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
if state:
manager.save_state(CoassembleResumeConfig(fanout_state=state))
@@ -243,9 +252,9 @@ def _trackings_resource(
job_id,
None,
resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
+ initial_paginator_state=_initial_fan_out_state(config, manager),
)
- return next(r for r in resources if r.name == "course_trackings")
+ return next(r for r in resources if r.name == config.name)
def coassemble_source(
@@ -257,11 +266,12 @@ def coassemble_source(
resumable_source_manager: ResumableSourceManager[CoassembleResumeConfig],
) -> SourceResponse:
config = COASSEMBLE_ENDPOINTS[endpoint]
+ client_config = _client_config(workspace_id, api_key)
- if config.fan_out_by_course:
- resource = _trackings_resource(workspace_id, api_key, team_id, job_id, resumable_source_manager)
+ if config.fan_out is not None:
+ resource = _fan_out_resource(client_config, config, team_id, job_id, resumable_source_manager)
else:
- resource = _standard_resource(workspace_id, api_key, endpoint, team_id, job_id, resumable_source_manager)
+ resource = _standard_resource(client_config, config, team_id, job_id, resumable_source_manager)
return SourceResponse(
name=endpoint,
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
index b3023a8908bc..8829b1ff8e97 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coassemble/settings.py
@@ -2,22 +2,48 @@ from dataclasses import dataclass, field
from products.warehouse_sources.backend.types import IncrementalField
+# The documented default page size for the list endpoints. We request it explicitly so the
+# "short page means last page" termination check compares against the size the server enforces.
+PAGE_SIZE = 100
+# /usage/clients documents a smaller default; requesting more risks a silently capped page being
+# read as the end of the collection.
+USAGE_PAGE_SIZE = 50
-@dataclass
+
+@dataclass(frozen=True)
+class CoassembleFanOut:
+ """A child endpoint that can only be listed per parent row, so the sync walks a parent endpoint
+ and calls the child once per row."""
+
+ # Key in COASSEMBLE_ENDPOINTS of the endpoint supplying the parent rows.
+ parent: str
+ # Parent field bound into the child path, and the placeholder in that path it fills.
+ resolve_field: str
+ param: str
+ # Column the parent value is stamped onto each child row as — child rows carry no reference
+ # back to the parent they were listed under.
+ stamp_column: str
+
+
+@dataclass(frozen=True)
class CoassembleEndpointConfig:
name: str
+ # Request path; for a fan-out child, a template over the fan-out's `param`.
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
+ # None when the endpoint documents no page/length params, so it serves a single page.
+ page_size: int | None = PAGE_SIZE
+ # Set when rows arrive inside an envelope rather than as a bare JSON array.
+ data_selector: str | None = None
+ fan_out: CoassembleFanOut | None = None
# 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
+# only: the courses/collections/clients/users lists expose no server-side timestamp filter, 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.
+# and the usage `start`/`end` params select a consumption window rather than a modified-since
+# cutoff — none of which we could 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"),
@@ -31,9 +57,56 @@ COASSEMBLE_ENDPOINTS: dict[str, CoassembleEndpointConfig] = {
# it is part of the key because tracking `id` uniqueness across courses is undocumented.
"course_trackings": CoassembleEndpointConfig(
name="course_trackings",
- path="/trackings",
+ path="/trackings?id={id}",
+ primary_keys=["course_id", "id"],
+ fan_out=CoassembleFanOut(parent="courses", resolve_field="id", param="id", stamp_column="course_id"),
+ ),
+ # Per-learner screen progress for a course: one row per learner, with the screen attempts and
+ # per-question progress nested under `attempts`.
+ "screen_trackings": CoassembleEndpointConfig(
+ name="screen_trackings",
+ path="/screen/trackings?id={id}",
primary_keys=["course_id", "id"],
- fan_out_by_course=True,
+ fan_out=CoassembleFanOut(parent="courses", resolve_field="id", param="id", stamp_column="course_id"),
+ ),
+ "collection_trackings": CoassembleEndpointConfig(
+ name="collection_trackings",
+ path="/collection/trackings?id={id}",
+ primary_keys=["collection_id", "id"],
+ fan_out=CoassembleFanOut(parent="collections", resolve_field="id", param="id", stamp_column="collection_id"),
+ ),
+ # /user/trackings answers for one learner and wraps their course trackings in a per-user
+ # envelope, so the rows are the envelope's `trackings` entries.
+ "user_trackings": CoassembleEndpointConfig(
+ name="user_trackings",
+ path="/user/trackings?identifier={identifier}",
+ primary_keys=["user_identifier", "id"],
+ data_selector="trackings",
+ fan_out=CoassembleFanOut(
+ parent="users", resolve_field="identifier", param="identifier", stamp_column="user_identifier"
+ ),
+ ),
+ # Consumption rows for every client in the workspace, one per metric per billing period.
+ "client_usage": CoassembleEndpointConfig(
+ name="client_usage",
+ path="/usage/clients",
+ primary_keys=["clientIdentifier", "metric", "periodStart"],
+ page_size=USAGE_PAGE_SIZE,
+ data_selector="data",
+ ),
+ # The per-client limits behind those consumption rows. Only addressable one client at a time,
+ # and the rows name no client, so the fan-out stamps `clientIdentifier` back in.
+ "client_allowances": CoassembleEndpointConfig(
+ name="client_allowances",
+ path="/usage/client/{identifier}",
+ primary_keys=["clientIdentifier", "metric", "periodStart"],
+ page_size=None,
+ fan_out=CoassembleFanOut(
+ parent="clients",
+ resolve_field="clientIdentifier",
+ param="identifier",
+ stamp_column="clientIdentifier",
+ ),
),
}
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 822cf887eeda..5c0c0223fddb 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
@@ -51,7 +51,7 @@ class CoassembleSource(ResumableSource[CoassembleSourceConfig, CoassembleResumeC
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.
+ caption="""Enter your Coassemble workspace ID and API key to pull your courses, collections, learners, learner progress, and client usage 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.
""",
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
index c17f7509507e..4e445e933f8c 100644
--- 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
@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble
from products.warehouse_sources.backend.temporal.data_imports.sources.coassemble.settings import (
COASSEMBLE_ENDPOINTS,
ENDPOINTS,
+ USAGE_PAGE_SIZE,
)
# RESTClient builds its session via make_tracked_session in the rest_client module.
@@ -276,7 +277,7 @@ class TestTrackingFanOut:
@mock.patch(CLIENT_SESSION_PATCH)
def test_page_cap_stops_runaway_course(self, MockSession: mock.MagicMock) -> None:
- with mock.patch.object(coassemble, "MAX_TRACKING_PAGES_PER_COURSE", 2):
+ with mock.patch.object(coassemble, "MAX_FAN_OUT_PAGES_PER_PARENT", 2):
session = MockSession.return_value
# Every trackings page is full, so without the cap this would page forever.
_wire(
@@ -294,6 +295,143 @@ class TestTrackingFanOut:
assert session.send.call_count == 3 # 1 courses page + 2 capped trackings pages
+class TestFanOutEndpointShapes:
+ @parameterized.expand(
+ [
+ (
+ "screen_trackings",
+ "/courses",
+ {"id": 11},
+ "/screen/trackings?id=11",
+ {"id": 1},
+ {"id": 1, "course_id": 11},
+ ),
+ (
+ "collection_trackings",
+ "/collections",
+ {"id": 7},
+ "/collection/trackings?id=7",
+ {"id": 1},
+ {"id": 1, "collection_id": 7},
+ ),
+ (
+ "client_allowances",
+ "/clients",
+ {"clientIdentifier": "acme"},
+ "/usage/client/acme",
+ {"metric": "ir", "limit": 10},
+ {"metric": "ir", "limit": 10, "clientIdentifier": "acme"},
+ ),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_parent_and_stamps_parent_reference(
+ self,
+ endpoint: str,
+ parent_path: str,
+ parent_row: dict[str, Any],
+ child_path: str,
+ child_row: dict[str, Any],
+ expected_row: dict[str, Any],
+ MockSession: mock.MagicMock,
+ ) -> None:
+ # Child rows name no parent, so a wrong resolve field or path template would either 404 or
+ # land rows whose primary key is half null.
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([parent_row]), _response([child_row])])
+
+ rows = _rows(endpoint, _make_manager())
+
+ assert rows == [expected_row]
+ assert [s["url"] for s in snapshots] == [
+ f"{COASSEMBLE_BASE_URL}{parent_path}",
+ f"{COASSEMBLE_BASE_URL}{child_path}",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_user_trackings_reads_rows_from_the_per_user_envelope(self, MockSession: mock.MagicMock) -> None:
+ # /user/trackings answers with one object per learner; the rows are its `trackings` entries,
+ # not the envelope itself.
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"identifier": "u-1"}]),
+ _response(
+ {
+ "identifier": "u-1",
+ "totals": {"viewed": 2, "completed": 1},
+ "trackings": [{"id": 5, "courseId": 9}],
+ }
+ ),
+ ],
+ )
+
+ rows = _rows("user_trackings", _make_manager())
+
+ assert rows == [{"id": 5, "courseId": 9, "user_identifier": "u-1"}]
+ assert snapshots[1]["url"] == f"{COASSEMBLE_BASE_URL}/user/trackings?identifier=u-1"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_client_allowances_reads_each_client_once_without_paging_params(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"clientIdentifier": "a"}, {"clientIdentifier": "b"}]),
+ _response([{"metric": "ir"}]),
+ _response([{"metric": "ir"}]),
+ ],
+ )
+
+ rows = _rows("client_allowances", _make_manager())
+
+ assert len(rows) == 2
+ # The endpoint documents no page/length params, so none are sent and each client is read once.
+ assert [s["params"] for s in snapshots if "/usage/client/" in s["url"]] == [{}, {}]
+ assert session.send.call_count == 3
+
+
+class TestClientUsagePagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_reads_rows_from_the_data_envelope(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ row = {"clientIdentifier": "acme", "metric": "ir", "currentUsage": 3}
+ snapshots = _wire(session, [_response({"page": 0, "length": USAGE_PAGE_SIZE, "data": [row]})])
+
+ rows = _rows("client_usage", _make_manager())
+
+ assert rows == [row]
+ # /usage/clients serves a smaller default page than the other list endpoints; requesting
+ # more would let a server-capped full page read as the end of the collection.
+ assert snapshots[0]["params"] == {"page": 0, "length": USAGE_PAGE_SIZE}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_page_advances_until_short_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ full = [{"clientIdentifier": f"c-{i}", "metric": "ir"} for i in range(USAGE_PAGE_SIZE)]
+ snapshots = _wire(
+ session,
+ [
+ _response({"page": 0, "length": USAGE_PAGE_SIZE, "data": full}),
+ _response({"page": 1, "length": USAGE_PAGE_SIZE, "data": [{"clientIdentifier": "z", "metric": "ir"}]}),
+ ],
+ )
+
+ rows = _rows("client_usage", _make_manager())
+
+ assert len(rows) == USAGE_PAGE_SIZE + 1
+ assert [s["params"]["page"] for s in snapshots] == [0, 1]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_envelope_key_fails_loudly(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response({"page": 0, "length": USAGE_PAGE_SIZE})])
+
+ with pytest.raises(ValueError, match="Required data_selector"):
+ _rows("client_usage", _make_manager())
+
+
class TestValidateCredentials:
@parameterized.expand(
[