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): add northpass lesson-level progress table (#79999)

jake sciotto446b8c019675
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/canonical_descriptions.py
index f97348757c23..eb747e0e9fc5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/canonical_descriptions.py
@@ -125,4 +125,24 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"last_active_on": "Timestamp of the person's last activity in the learning path.",
},
},
+ "course_activities": {
+ "description": "Activities (lessons) that make up each course, one row per activity. Fanned out per course.",
+ "docs_url": "https://developers.northpass.com/reference/get_v2-courses-course-uuid-activities",
+ "columns": {
+ "id": "Unique identifier (UUID) for the activity.",
+ "type": "JSON:API resource type, always 'activities'.",
+ "title": "The activity title.",
+ "course_id": "UUID of the course the activity belongs to.",
+ },
+ },
+ "activity_events": {
+ "description": "Lesson-level learning events, one row per person, activity, and timestamp (e.g. a learner viewed an activity).",
+ "docs_url": "https://developers.northpass.com/reference/get_v2-events",
+ "columns": {
+ "type": "Event type (e.g. 'learner_viewed_activity_events').",
+ "created_at": "Timestamp when the event occurred.",
+ "person_id": "UUID of the person the event belongs to.",
+ "activity_id": "UUID of the activity (lesson) the event relates to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/northpass_lms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/northpass_lms.py
index 807d7353dfbd..4f5a5e66d836 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/northpass_lms.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/northpass_lms.py
@@ -71,6 +71,27 @@ def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:
return row
+def _make_relationship_flattener(relationship_id_fields: dict[str, str]) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ """Flatten a row and promote related-resource ids from ``relationships`` to root columns.
+
+ ``/events`` rows carry no ``id`` and reference the person/activity they belong to only inside
+ JSON:API ``relationships``; promoting those ids gives the row queryable foreign-key columns
+ (which also form its primary key). A missing relationship still emits its column (``None``) so
+ the table schema stays stable across heterogeneous event types.
+ """
+
+ def _flatten(item: dict[str, Any]) -> dict[str, Any]:
+ row = _flatten_item(item)
+ relationships = row.get("relationships")
+ for relationship, column in relationship_id_fields.items():
+ related = relationships.get(relationship) if isinstance(relationships, dict) else None
+ data = related.get("data") if isinstance(related, dict) else None
+ row[column] = data.get("id") if isinstance(data, dict) else None
+ return row
+
+ return _flatten
+
+
def _make_child_flattener(parent_name: str, parent_id_field: str) -> Callable[[dict[str, Any]], dict[str, Any]]:
"""Flatten a fan-out child row and rename its injected parent id.
@@ -114,6 +135,9 @@ def _top_level_source(
resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],
db_incremental_field_last_value: Optional[Any],
) -> Resource:
+ data_map = (
+ _make_relationship_flattener(config.relationship_id_fields) if config.relationship_id_fields else _flatten_item
+ )
rest_config: RESTAPIConfig = {
"client": _client_config(api_key),
# A collection with no rows 404s instead of returning `data: []` (seen on
@@ -130,7 +154,7 @@ def _top_level_source(
# `.get("data", [])`), so no data_selector_required here.
"data_selector": "data",
},
- "data_map": _flatten_item,
+ "data_map": data_map,
}
],
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/settings.py
index 83418986c365..eedb8a6b852e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/settings.py
@@ -23,6 +23,10 @@ class NorthpassEndpointConfig:
# name under which the parent id is injected into each child row (also part of the primary key).
fan_out_parent: Optional[str] = None
parent_id_field: Optional[str] = None
+ # For endpoints whose rows reference other resources only inside JSON:API `relationships`
+ # (e.g. `/events` rows carry no `id` of their own): relationship name -> column name under
+ # which the related resource's id is promoted to the row root.
+ relationship_id_fields: Optional[dict[str, str]] = None
# Human-readable note surfaced in the schema picker / docs.
description: Optional[str] = None
@@ -79,6 +83,31 @@ NORTHPASS_ENDPOINTS: dict[str, NorthpassEndpointConfig] = {
parent_id_field="learning_path_id",
description="Enrollments for every learning path. Fans out one request per learning path. Full refresh only.",
),
+ # Lesson-level progress. `course_activities` is the per-course lesson catalog (the API exposes
+ # no timestamps on activities, so no partitioning), and `activity_events` is the learning-event
+ # stream recording who did what on which activity when.
+ "course_activities": NorthpassEndpointConfig(
+ name="course_activities",
+ path="/courses/{parent_id}/activities",
+ primary_keys=["course_id", "id"],
+ fan_out_parent="courses",
+ parent_id_field="course_id",
+ description="Activities (lessons) that make up every course. Fans out one request per course. Full refresh only.",
+ ),
+ "activity_events": NorthpassEndpointConfig(
+ name="activity_events",
+ path="/events",
+ partition_key="created_at",
+ # Events carry no id of their own; the (person, activity, type, time) grain is the closest
+ # stable key. Full-refresh writes never dedupe on primary keys, so exact duplicates land
+ # as-is (harmless for an event stream).
+ primary_keys=["person_id", "activity_id", "type", "created_at"],
+ # The endpoint has no server-side filter, so every sync re-fetches the full event history —
+ # potentially very large, so users opt in per schema.
+ should_sync_default=False,
+ relationship_id_fields={"person": "person_id", "activity": "activity_id"},
+ description="Lesson-level learning events (e.g. learner viewed an activity), one row per person, activity, and timestamp. Re-syncs the full history on every run, so it is off by default.",
+ ),
}
ENDPOINTS = tuple(NORTHPASS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms.py
index 8d430a9209da..7e0d4d4af512 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms.py
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_
_build_url,
_flatten_item,
_make_child_flattener,
+ _make_relationship_flattener,
northpass_source,
)
@@ -106,6 +107,41 @@ class TestFlattenItem:
assert row == {"id": "x", "type": "quizzes"}
+class TestRelationshipFlattener:
+ def test_promotes_relationship_ids_to_root_columns(self):
+ flatten = _make_relationship_flattener({"person": "person_id", "activity": "activity_id"})
+ row = flatten(
+ {
+ "type": "learner_viewed_activity_events",
+ "attributes": {"created_at": "2024-10-08T08:37:24Z"},
+ "relationships": {
+ "person": {"data": {"type": "people", "id": "p1"}},
+ "activity": {"data": {"type": "activities", "id": "a1"}},
+ },
+ }
+ )
+
+ # These columns form the endpoint's primary key, so they must land at the row root.
+ assert row["person_id"] == "p1"
+ assert row["activity_id"] == "a1"
+ assert row["created_at"] == "2024-10-08T08:37:24Z"
+
+ @parameterized.expand(
+ [
+ ("no_relationships_block", {"type": "x", "attributes": {"created_at": "t"}}),
+ ("relationship_missing", {"type": "x", "relationships": {"person": {"data": {"id": "p1"}}}}),
+ ("relationship_data_null", {"type": "x", "relationships": {"activity": {"data": None}}}),
+ ]
+ )
+ def test_missing_relationship_still_emits_column(self, _name, item):
+ flatten = _make_relationship_flattener({"activity": "activity_id"})
+ row = flatten(item)
+
+ # The column must exist (as None) even when the event has no such relationship, so the
+ # table schema stays stable across heterogeneous event types.
+ assert row["activity_id"] is None
+
+
class TestChildFlattener:
def test_renames_injected_parent_id_and_flattens(self):
flatten = _make_child_flattener("courses", "course_id")
@@ -281,6 +317,62 @@ class TestFanOut:
assert rows == []
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_course_activities_rows_carry_course_id_and_title(self, mock_make_session):
+ pages = {
+ "https://api.northpass.com/v2/courses?limit=100": _page([{"id": "c1"}, {"id": "c2"}]),
+ "https://api.northpass.com/v2/courses/c1/activities?limit=100": _page(
+ [{"id": "a1", "type": "activities", "attributes": {"title": "Lesson 1"}}]
+ ),
+ "https://api.northpass.com/v2/courses/c2/activities?limit=100": _page(
+ [{"id": "a2", "type": "activities", "attributes": {"title": "Lesson 2"}}]
+ ),
+ }
+ _wire(mock_make_session, pages)
+
+ rows = _rows("course_activities", _make_manager())
+
+ # The injected course id keeps the [course_id, id] primary key unique table-wide.
+ assert [(r["id"], r["course_id"], r["title"]) for r in rows] == [
+ ("a1", "c1", "Lesson 1"),
+ ("a2", "c2", "Lesson 2"),
+ ]
+
+
+class TestActivityEvents:
+ EVENTS_P1 = "https://api.northpass.com/v2/events?limit=100"
+ EVENTS_P2 = "https://api.northpass.com/v2/events?page=2&limit=100"
+
+ @staticmethod
+ def _event(person_id: str, activity_id: str, created_at: str) -> dict[str, Any]:
+ return {
+ "type": "learner_viewed_activity_events",
+ "attributes": {"created_at": created_at},
+ "relationships": {
+ "person": {"data": {"type": "people", "id": person_id}},
+ "activity": {"data": {"type": "activities", "id": activity_id}},
+ },
+ }
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_yields_rows_keyed_by_person_activity_and_time(self, mock_make_session):
+ pages = {
+ self.EVENTS_P1: _page([self._event("p1", "a1", "2024-10-08T08:37:24Z")], next_url=self.EVENTS_P2),
+ self.EVENTS_P2: _page([self._event("p2", "a1", "2024-10-08T09:00:00Z")]),
+ }
+ sent = _wire(mock_make_session, pages)
+
+ rows = _rows("activity_events", _make_manager())
+
+ # Rows land with the person/activity ids promoted out of `relationships` — the columns the
+ # composite primary key and any join to `course_activities` / `people` depend on.
+ assert [(r["person_id"], r["activity_id"], r["created_at"]) for r in rows] == [
+ ("p1", "a1", "2024-10-08T08:37:24Z"),
+ ("p2", "a1", "2024-10-08T09:00:00Z"),
+ ]
+ assert all(r["type"] == "learner_viewed_activity_events" for r in rows)
+ assert sent == [self.EVENTS_P1, self.EVENTS_P2]
+
class TestNorthpassSource:
@parameterized.expand(
@@ -289,12 +381,19 @@ class TestNorthpassSource:
("courses", ["id"], "created_at"),
("course_enrollments", ["course_id", "id"], "enrolled_at"),
("learning_path_enrollments", ["learning_path_id", "id"], "enrolled_at"),
+ ("activity_events", ["person_id", "activity_id", "type", "created_at"], "created_at"),
+ # The v2 API exposes no timestamps on activities, so the catalog is unpartitioned.
+ ("course_activities", ["course_id", "id"], None),
]
)
def test_source_response_carries_endpoint_keys_and_partitioning(self, endpoint, primary_keys, partition_key):
response = northpass_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager())
assert response.name == endpoint
assert response.primary_keys == primary_keys
- assert response.partition_keys == [partition_key]
- assert response.partition_mode == "datetime"
- assert response.partition_format == "month"
+ if partition_key is None:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+ else:
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms_source.py
index b214195a8852..6cb19416edee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms_source.py
@@ -83,6 +83,17 @@ class TestNorthpassLMSSource:
assert schemas["people"].detected_primary_keys == ["id"]
assert schemas["course_enrollments"].detected_primary_keys == ["course_id", "id"]
assert schemas["learning_path_enrollments"].detected_primary_keys == ["learning_path_id", "id"]
+ assert schemas["course_activities"].detected_primary_keys == ["course_id", "id"]
+ # Events carry no id of their own, so the key is the full (who, what, when) grain.
+ assert schemas["activity_events"].detected_primary_keys == ["person_id", "activity_id", "type", "created_at"]
+
+ def test_activity_events_is_the_only_schema_off_by_default(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ # The event stream re-fetches its full history every sync, so connecting the source must
+ # not silently enable it; everything else keeps syncing by default.
+ off_by_default = {schema.name for schema in schemas if not schema.should_sync_default}
+ assert off_by_default == {"activity_events"}
def test_get_schemas_filtered_by_names(self):
schemas = self.source.get_schemas(self.config, self.team_id, names=["courses"])