:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add northpass quiz attempts and answers tables (#80012)
jake sciottoa9daa66182a9
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.pyindex eb747e0e9fc5..1127306f9964 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@@ -145,4 +145,35 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"activity_id": "UUID of the activity (lesson) the event relates to.",},},+ "quiz_attempts": {+ "description": "Completed quiz attempts, one row per attempt, built from the quiz-completed events in the sent-webhooks log (last three months).",+ "docs_url": "https://developers.northpass.com/docs/webhook-payloads",+ "columns": {+ "id": "Unique identifier (UUID) for the quiz attempt.",+ "type": "Event type the row was built from, always 'quiz_completed_events'.",+ "event_id": "UUID of the quiz-completed event that recorded the attempt.",+ "value": "The learner's score on the attempt.",+ "minimum_passing_score": "Minimum score required to pass the quiz.",+ "attempts_remaining": "Number of attempts the learner had left after this one.",+ "created_at": "Timestamp when the attempt was completed.",+ "quiz_id": "UUID of the quiz attempted.",+ "course_id": "UUID of the course the quiz belongs to.",+ "person_id": "UUID of the learner who took the quiz.",+ "activity_id": "UUID of the activity (lesson) the quiz is attached to.",+ },+ },+ "quiz_attempt_answers": {+ "description": "Learner answers for each completed quiz attempt, one row per question answered. Fanned out per quiz attempt.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-quiz-attempts-quiz-attempt-uuid-answers",+ "columns": {+ "id": "Unique identifier (UUID) for the answer.",+ "type": "JSON:API resource type, always 'learner_answers'.",+ "quiz_attempt_id": "UUID of the quiz attempt the answer belongs to.",+ "question_id": "UUID of the question answered.",+ "value": "The answer the learner gave.",+ "values": "Selected answer options, each with the answer text and its possible answer id.",+ "correct": "Whether the answer was correct.",+ "created_at": "Timestamp when the answer was recorded.",+ },+ },}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.pyindex 4f5a5e66d836..861c87a8f1ee 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@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.soufrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.settings import (NORTHPASS_ENDPOINTS,+ QUIZ_COMPLETED_EVENT_TYPE,NorthpassEndpointConfig,)@@ -110,6 +111,102 @@ def _make_child_flattener(parent_name: str, parent_id_field: str) -> Callable[[dreturn _flatten+def _promote_relationship_ids(row: dict[str, Any], relationship_id_fields: dict[str, str]) -> dict[str, Any]:+ """Promote related-resource ids out of a row's JSON:API ``relationships`` into root columns.++ Gives rows queryable foreign-key columns. A missing relationship still emits its column+ (``None``) so the table schema stays stable across rows.+ """+ 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+++def _make_quiz_attempt_flattener() -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:+ """Reshape sent-webhooks log messages into completed-quiz-attempt rows.++ The v2 API lists no quiz attempts directly; the quiz-completed event a ``/webhooks`` message+ delivered (in ``attributes.payload``) is the only documented place attempt UUIDs and results+ appear. The attempt UUID becomes the row ``id`` — the primary key, and what the answers fan-out+ resolves — with the event's own id kept as ``event_id`` and the quiz/course/person/activity+ references promoted to id columns. A message maps to ``[]`` (dropping it) when it carries+ another event type (in case the server ever ignores the type filter), when its payload has no+ attempt UUID, or when the attempt was already seen this run — the log stores one message per+ subscribed webhook endpoint, so the same attempt can appear more than once.+ """+ seen: set[str] = set()++ def _flatten(item: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:+ message = item.get("attributes")+ if not isinstance(message, dict) or message.get("type") != QUIZ_COMPLETED_EVENT_TYPE:+ return []+ payload = message.get("payload")+ event = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(event, dict):+ return []+ attributes = event.get("attributes")+ if not isinstance(attributes, dict):+ return []+ attempt_id = attributes.get("quiz_attempt_uuid")+ if not attempt_id or attempt_id in seen:+ return []+ seen.add(attempt_id)++ row: dict[str, Any] = {key: value for key, value in attributes.items() if key != "quiz_attempt_uuid"}+ # Set after the attribute spread so the attempt id always wins as ``id``.+ row.update(+ {+ "id": attempt_id,+ "type": event.get("type"),+ "event_id": event.get("id"),+ "relationships": event.get("relationships"),+ }+ )+ return _promote_relationship_ids(+ row, {"quiz": "quiz_id", "course": "course_id", "person": "person_id", "activity": "activity_id"}+ )++ return _flatten+++def _make_quiz_answer_flattener(parent_name: str, parent_id_field: str) -> Callable[[dict[str, Any]], dict[str, Any]]:+ """Child flattener for quiz answers: standard child flattening plus a promoted ``question_id``.++ An answer references its question only inside JSON:API ``relationships``; promoting the id to a+ root column keeps answers joinable to their question.+ """+ flatten_child = _make_child_flattener(parent_name, parent_id_field)++ def _flatten(item: dict[str, Any]) -> dict[str, Any]:+ return _promote_relationship_ids(flatten_child(item), {"question": "question_id"})++ return _flatten+++def _collection_params(config: NorthpassEndpointConfig) -> dict[str, Any]:+ return dict(config.params) if config.params is not None else {"limit": PAGE_SIZE}+++def _collection_data_map(+ endpoint: str,+) -> Optional[Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]]:+ """Bespoke row transform for a collection endpoint, or None when raw JSON:API items are fine."""+ if endpoint == "quiz_attempts":+ return _make_quiz_attempt_flattener()+ return None+++def _child_data_map(+ endpoint: str, parent_name: str, parent_id_field: str+) -> Callable[[dict[str, Any]], dict[str, Any]]:+ if endpoint == "quiz_attempt_answers":+ return _make_quiz_answer_flattener(parent_name, parent_id_field)+ return _make_child_flattener(parent_name, parent_id_field)++def _client_config(api_key: str) -> ClientConfig:return {"base_url": NORTHPASS_BASE_URL,@@ -135,7 +232,7 @@ def _top_level_source(resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],db_incremental_field_last_value: Optional[Any],) -> Resource:- data_map = (+ data_map = _collection_data_map(endpoint) or (_make_relationship_flattener(config.relationship_id_fields) if config.relationship_id_fields else _flatten_item)rest_config: RESTAPIConfig = {@@ -149,7 +246,7 @@ def _top_level_source("name": endpoint,"endpoint": {"path": config.path,- "params": {"limit": PAGE_SIZE},+ "params": _collection_params(config),# A 200 without `data` is treated as an empty page (old transport used# `.get("data", [])`), so no data_selector_required here."data_selector": "data",@@ -206,9 +303,12 @@ def _fan_out_source("name": parent_name,"endpoint": {"path": parent_config.path,- "params": {"limit": PAGE_SIZE},+ "params": _collection_params(parent_config),"data_selector": "data",},+ # Parents that aren't plain JSON:API collections (the sent-webhooks log backing+ # quiz_attempts) are reshaped before the child resolves ids from their rows.+ "data_map": _collection_data_map(parent_name),},{"name": endpoint,@@ -224,7 +324,7 @@ def _fan_out_source(# as a valid empty page and move on to the next parent rather than failing the sync."response_actions": [{"status_code": 404, "action": "ignore"}],},- "data_map": _make_child_flattener(parent_name, config.parent_id_field),+ "data_map": _child_data_map(endpoint, parent_name, config.parent_id_field),},],}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.pyindex eedb8a6b852e..7b38fc8272ac 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@@ -1,5 +1,5 @@from dataclasses import dataclass, field-from typing import Optional+from typing import Any, Optionalfrom products.warehouse_sources.backend.types import IncrementalField@@ -14,6 +14,9 @@ class NorthpassEndpointConfig:# JSON:API collection path relative to the API base. Fan-out children use a `{parent_id}`# placeholder resolved per parent resource.path: str+ # Query params for the collection request; None means the default page-size param. Fan-out+ # child requests always use the default.+ params: Optional[dict[str, Any]] = None# Stable creation-time field used for datetime partitioning. Never `updated_at` — it moves and# would rewrite partitions on every sync.partition_key: Optional[str] = None@@ -31,6 +34,14 @@ class NorthpassEndpointConfig:description: Optional[str] = None+# The v2 API has no endpoint that lists quiz attempts, and no resource (quizzes, people,+# enrollments, activities) references them. The only documented place attempt UUIDs and results+# appear is the quiz-completed event stream in the sent-webhooks log (`GET /v2/webhooks`), which+# requires a webhook endpoint subscribed to these events and retains three months of messages.+QUIZ_COMPLETED_EVENT_TYPE = "quiz_completed_events"+# `/webhooks` documents a maximum page size of 50, unlike the other list endpoints.+WEBHOOKS_PAGE_SIZE = 50+NORTHPASS_ENDPOINTS: dict[str, NorthpassEndpointConfig] = {"people": NorthpassEndpointConfig(name="people",@@ -108,6 +119,38 @@ NORTHPASS_ENDPOINTS: dict[str, NorthpassEndpointConfig] = {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.",),+ # Quiz attempts & answers. `quiz_attempts` rows are reshaped from the quiz-completed events in+ # the sent-webhooks log (see `_make_quiz_attempt_flattener`), and `quiz_attempt_answers` fans+ # out over those attempts for per-question answers. Both are off by default: the log only+ # covers accounts with a quiz-completed webhook subscription and its trailing three months, and+ # the answers fan-out costs one request per attempt on every sync.+ "quiz_attempts": NorthpassEndpointConfig(+ name="quiz_attempts",+ path="/webhooks",+ params={"filter[type][in]": QUIZ_COMPLETED_EVENT_TYPE, "limit": WEBHOOKS_PAGE_SIZE},+ partition_key="created_at",+ should_sync_default=False,+ description=(+ "Completed quiz attempts with score and passing threshold, one row per attempt. Built from "+ "quiz-completed events in the sent-webhooks log, which requires a webhook subscribed to "+ "those events and keeps three months of history, so the table is off by default. Full "+ "refresh only."+ ),+ ),+ "quiz_attempt_answers": NorthpassEndpointConfig(+ name="quiz_attempt_answers",+ path="/quiz_attempts/{parent_id}/answers",+ partition_key="created_at",+ primary_keys=["quiz_attempt_id", "id"],+ fan_out_parent="quiz_attempts",+ parent_id_field="quiz_attempt_id",+ should_sync_default=False,+ description=(+ "Per-question learner answers for every completed quiz attempt. Fans out one request per "+ "attempt found in the sent-webhooks log (same coverage caveats as quiz_attempts), so the "+ "table is off by default. Full refresh only."+ ),+ ),}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.pyindex 7e0d4d4af512..b31c5b3b92c7 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_quiz_attempt_flattener,_make_relationship_flattener,northpass_source,)@@ -374,6 +375,177 @@ class TestActivityEvents:assert sent == [self.EVENTS_P1, self.EVENTS_P2]+def _quiz_message(+ attempt_id: str | None,+ message_id: str = "m1",+ event_type: str = "quiz_completed_events",+ relationships: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """A sent-webhooks log message carrying a quiz-completed event payload."""+ attributes: dict[str, Any] = {+ "value": 100,+ "created_at": "2024-10-08T08:37:45Z",+ "attempts_remaining": 0,+ "minimum_passing_score": 80,+ }+ if attempt_id is not None:+ attributes["quiz_attempt_uuid"] = attempt_id+ return {+ "id": message_id,+ "type": "webhook",+ "attributes": {+ "attempt_left": 1,+ "created_at": "2024-10-08T08:37:45.656Z",+ "received_at": "2024-10-08T08:37:45.644Z",+ "type": event_type,+ "url": "https://example.com/hook",+ "payload": {+ "data": {+ "id": f"evt-{message_id}",+ "type": event_type,+ "attributes": attributes,+ "relationships": relationships+ if relationships is not None+ else {+ "quiz": {"data": {"type": "quizzes", "id": "q1"}},+ "course": {"data": {"type": "courses", "id": "c1"}},+ "person": {"data": {"type": "people", "id": "p1"}},+ "activity": {"data": {"type": "activities", "id": "a1"}},+ },+ }+ },+ },+ }+++def _message_without_payload() -> dict[str, Any]:+ message = _quiz_message("at1")+ del message["attributes"]["payload"]+ return message+++class TestQuizAttemptFlattener:+ def test_reshapes_webhook_message_into_attempt_row(self):+ row = _make_quiz_attempt_flattener()(_quiz_message("at1"))++ assert isinstance(row, dict)+ # The attempt UUID must land as `id` — it is the primary key and what the answers fan-out+ # resolves; the message's own delivery id must not leak into the row.+ assert row["id"] == "at1"+ assert row["event_id"] == "evt-m1"+ assert row["type"] == "quiz_completed_events"+ assert row["value"] == 100+ assert row["minimum_passing_score"] == 80+ assert row["attempts_remaining"] == 0+ assert row["created_at"] == "2024-10-08T08:37:45Z"+ assert (row["quiz_id"], row["course_id"], row["person_id"], row["activity_id"]) == ("q1", "c1", "p1", "a1")++ @parameterized.expand(+ [+ ("other_event_type", _quiz_message("at1", event_type="course_completed_events")),+ ("no_payload", _message_without_payload()),+ ("payload_without_attempt_uuid", _quiz_message(None)),+ ]+ )+ def test_drops_unusable_messages(self, _name, message):+ # A message that can't yield an attempt row must be dropped, not emitted — a row without an+ # `id` would fail the fan-out's parent resolution and corrupt the primary key.+ assert _make_quiz_attempt_flattener()(message) == []++ def test_dedupes_attempts_across_messages_within_a_run(self):+ flatten = _make_quiz_attempt_flattener()++ first = flatten(_quiz_message("at1", message_id="m1"))+ second = flatten(_quiz_message("at1", message_id="m2"))++ # The log stores one message per subscribed webhook endpoint, so the same attempt can+ # appear twice; only the first delivery may produce a row.+ assert isinstance(first, dict)+ assert second == []++ def test_seen_state_is_fresh_per_flattener(self):+ # Each sync builds its own flattener; a shared seen-set would make every sync after the+ # first in a long-lived worker yield an empty table.+ assert isinstance(_make_quiz_attempt_flattener()(_quiz_message("at1")), dict)+ assert isinstance(_make_quiz_attempt_flattener()(_quiz_message("at1")), dict)++ def test_missing_relationships_still_emit_id_columns(self):+ row = _make_quiz_attempt_flattener()(_quiz_message("at1", relationships={}))++ assert isinstance(row, dict)+ # Columns must exist (as None) even when a reference is absent, so the table schema stays+ # stable across events.+ assert (row["quiz_id"], row["course_id"], row["person_id"], row["activity_id"]) == (None, None, None, None)+++WEBHOOKS_URL = "https://api.northpass.com/v2/webhooks?filter%5Btype%5D%5Bin%5D=quiz_completed_events&limit=50"+++class TestQuizAttemptsAndAnswers:+ def _log_and_answers(self) -> dict[str, Any]:+ return {+ WEBHOOKS_URL: _page(+ [+ _quiz_message("at1", message_id="m1"),+ # A second delivery of the same attempt (another subscribed endpoint) and a+ # non-quiz message that slipped past the server-side type filter.+ _quiz_message("at1", message_id="m2"),+ _quiz_message("at9", message_id="m3", event_type="course_completed_events"),+ _quiz_message("at2", message_id="m4"),+ ]+ ),+ "https://api.northpass.com/v2/quiz_attempts/at1/answers?limit=100": _page(+ [+ {+ "id": "ans1",+ "type": "learner_answers",+ "attributes": {"value": "New Answer", "correct": False, "created_at": "2024-10-08T08:37:34Z"},+ "relationships": {+ "question": {"data": {"type": "questions/choose", "id": "qq1"}},+ "quiz_attempt": {"data": {"type": "quiz_attempts", "id": "at1"}},+ },+ }+ ]+ ),+ "https://api.northpass.com/v2/quiz_attempts/at2/answers?limit=100": _page(+ # No question relationship: the promoted column must still exist (as None).+ [{"id": "ans2", "type": "learner_answers", "attributes": {"correct": True}}]+ ),+ }++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_quiz_attempts_syncs_from_filtered_webhooks_log(self, mock_make_session):+ sent = _wire(mock_make_session, self._log_and_answers())++ rows = _rows("quiz_attempts", _make_manager())++ # The duplicate delivery and the non-quiz message must not produce rows.+ assert [(r["id"], r["value"], r["person_id"]) for r in rows] == [("at1", 100, "p1"), ("at2", 100, "p1")]+ # The exact URL proves the type filter and the /webhooks 50-row page cap are sent.+ assert sent == [WEBHOOKS_URL]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_answers_fan_out_over_attempts_from_the_log(self, mock_make_session):+ sent = _wire(mock_make_session, self._log_and_answers())++ rows = _rows("quiz_attempt_answers", _make_manager())++ by_id = {r["id"]: r for r in rows}+ # Rows carry the injected attempt id (part of the primary key) and the promoted question id.+ assert by_id["ans1"]["quiz_attempt_id"] == "at1"+ assert by_id["ans1"]["question_id"] == "qq1"+ assert by_id["ans1"]["correct"] is False+ assert by_id["ans2"]["quiz_attempt_id"] == "at2"+ assert by_id["ans2"]["question_id"] is None+ # One answers request per unique attempt: the duplicate delivery and the non-quiz message+ # must not fan out.+ assert sent == [+ WEBHOOKS_URL,+ "https://api.northpass.com/v2/quiz_attempts/at1/answers?limit=100",+ "https://api.northpass.com/v2/quiz_attempts/at2/answers?limit=100",+ ]++class TestNorthpassSource:@parameterized.expand([@@ -384,6 +556,8 @@ class TestNorthpassSource:("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),+ ("quiz_attempts", ["id"], "created_at"),+ ("quiz_attempt_answers", ["quiz_attempt_id", "id"], "created_at"),])def test_source_response_carries_endpoint_keys_and_partitioning(self, endpoint, primary_keys, partition_key):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.pyindex 6cb19416edee..bb5c4777ae19 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@@ -86,14 +86,18 @@ class TestNorthpassLMSSource: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"]+ assert schemas["quiz_attempts"].detected_primary_keys == ["id"]+ assert schemas["quiz_attempt_answers"].detected_primary_keys == ["quiz_attempt_id", "id"]- def test_activity_events_is_the_only_schema_off_by_default(self):+ def test_costly_schemas_are_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.+ # The event stream re-fetches its full history every sync, and both quiz tables depend on+ # the sent-webhooks log (subscription required, three-month retention) with a per-attempt+ # fan-out, so connecting the source must not silently enable them; 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"}+ assert off_by_default == {"activity_events", "quiz_attempts", "quiz_attempt_answers"}def test_get_schemas_filtered_by_names(self):schemas = self.source.get_schemas(self.config, self.team_id, names=["courses"])