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.

fix(warehouse-sources): stop the Northpass webhooks walk on an empty page (#98072)

jake sciotto0110a7e17cba
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 861c87a8f1ee..7a1d6034536c 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
@@ -1,8 +1,10 @@
import dataclasses
-from collections.abc import Callable
+from collections.abc import Callable, Iterable, Iterator
from typing import Any, Optional
from urllib.parse import urlencode
+from requests import Response
+
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,
@@ -23,6 +25,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.settings import (
NORTHPASS_ENDPOINTS,
QUIZ_COMPLETED_EVENT_TYPE,
+ QUIZ_LOG_EMPTY_MESSAGE,
+ QUIZ_LOG_ENDPOINTS,
NorthpassEndpointConfig,
)
@@ -35,6 +39,35 @@ NORTHPASS_HOST = "api.northpass.com"
PAGE_SIZE = 100
+class NorthpassQuizLogEmptyError(Exception):
+ """The sent-webhooks log served no quiz-completed event, so the quiz tables have nothing to build from."""
+
+
+class NorthpassPaginator(JSONResponsePaginator):
+ """Follow JSON:API ``links.next``, and stop on an empty page even when a next link is present.
+
+ ``/webhooks`` keeps serving a next link after its last message, so a walk that trusts the link
+ alone never ends.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(next_url_path="links.next")
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if not data:
+ self._has_next_page = False
+ return
+ super().update_state(response, data)
+
+
+def _require_quiz_attempts(
+ pages: Iterable[list[dict[str, Any]]], endpoint: str, attempts_seen: set[str]
+) -> Iterator[list[dict[str, Any]]]:
+ yield from pages
+ if not attempts_seen:
+ raise NorthpassQuizLogEmptyError(f"{QUIZ_LOG_EMPTY_MESSAGE}, so {endpoint} has no rows to sync")
+
+
@dataclasses.dataclass
class NorthpassResumeConfig:
# Top-level endpoints: full URL of the next JSON:API page (`links.next`). None means "start from
@@ -125,7 +158,7 @@ def _promote_relationship_ids(row: dict[str, Any], relationship_id_fields: dict[
return row
-def _make_quiz_attempt_flattener() -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:
+def _make_quiz_attempt_flattener(seen: set[str]) -> 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
@@ -137,7 +170,6 @@ def _make_quiz_attempt_flattener() -> Callable[[dict[str, Any]], dict[str, Any]
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")
@@ -191,11 +223,11 @@ def _collection_params(config: NorthpassEndpointConfig) -> dict[str, Any]:
def _collection_data_map(
- endpoint: str,
+ endpoint: str, attempts_seen: set[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 _make_quiz_attempt_flattener(attempts_seen)
return None
@@ -215,7 +247,7 @@ def _client_config(api_key: str) -> ClientConfig:
"headers": {"Accept": "application/json"},
"auth": {"type": "api_key", "api_key": api_key, "name": "X-Api-Key", "location": "header"},
# JSON:API paginates via a `links.next` URL embedded in the response body.
- "paginator": JSONResponsePaginator(next_url_path="links.next"),
+ "paginator": NorthpassPaginator(),
# Pin every request to Northpass's host and refuse redirects, so a spoofed `next` link or a
# 30x can't forward the credentialed X-Api-Key header off-host.
"allowed_hosts": [NORTHPASS_HOST],
@@ -231,8 +263,9 @@ def _top_level_source(
job_id: str,
resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],
db_incremental_field_last_value: Optional[Any],
+ attempts_seen: set[str],
) -> Resource:
- data_map = _collection_data_map(endpoint) or (
+ data_map = _collection_data_map(endpoint, attempts_seen) or (
_make_relationship_flattener(config.relationship_id_fields) if config.relationship_id_fields else _flatten_item
)
rest_config: RESTAPIConfig = {
@@ -286,6 +319,7 @@ def _fan_out_source(
job_id: str,
resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],
db_incremental_field_last_value: Optional[Any],
+ attempts_seen: set[str],
) -> Resource:
if config.fan_out_parent is None or config.parent_id_field is None:
raise ValueError(f"_fan_out_source called with non-fan-out config: {config.name}")
@@ -308,7 +342,7 @@ def _fan_out_source(
},
# 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),
+ "data_map": _collection_data_map(parent_name, attempts_seen),
},
{
"name": endpoint,
@@ -360,19 +394,40 @@ def northpass_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = NORTHPASS_ENDPOINTS[endpoint]
+ attempts_seen: set[str] = set()
if config.fan_out_parent is not None:
resource = _fan_out_source(
- api_key, endpoint, config, team_id, job_id, resumable_source_manager, db_incremental_field_last_value
+ api_key,
+ endpoint,
+ config,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ db_incremental_field_last_value,
+ attempts_seen,
)
else:
resource = _top_level_source(
- api_key, endpoint, config, team_id, job_id, resumable_source_manager, db_incremental_field_last_value
+ api_key,
+ endpoint,
+ config,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ db_incremental_field_last_value,
+ attempts_seen,
)
+ items: Callable[[], Iterable[list[dict[str, Any]]]]
+ if endpoint in QUIZ_LOG_ENDPOINTS:
+ items = lambda: _require_quiz_attempts(resource, endpoint, attempts_seen)
+ else:
+ items = lambda: resource
+
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
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 7b38fc8272ac..3c7cb7d94abd 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
@@ -41,6 +41,10 @@ class NorthpassEndpointConfig:
QUIZ_COMPLETED_EVENT_TYPE = "quiz_completed_events"
# `/webhooks` documents a maximum page size of 50, unlike the other list endpoints.
WEBHOOKS_PAGE_SIZE = 50
+# Raised when the log walk ends with no quiz-completed event. `source.py` maps it to the operator
+# message, so the two must share this prefix.
+QUIZ_LOG_EMPTY_MESSAGE = "Northpass sent-webhooks log returned no quiz-completed events"
+QUIZ_LOG_ENDPOINTS = ("quiz_attempts", "quiz_attempt_answers")
NORTHPASS_ENDPOINTS: dict[str, NorthpassEndpointConfig] = {
"people": NorthpassEndpointConfig(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.py
index 842d90708e2d..21e12fe2784e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.py
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_
ENDPOINTS,
INCREMENTAL_FIELDS,
NORTHPASS_ENDPOINTS,
+ QUIZ_LOG_EMPTY_MESSAGE,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -89,6 +90,9 @@ You can create an API key in your Northpass admin panel under **Apps → API Acc
# sibling tables when Northpass gates an endpoint on an account plan (#87959). The
# message points the operator at the sibling-table check instead of blaming the key.
"403 Client Error: Forbidden for url: https://api.northpass.com": "Northpass refused access to the endpoint behind this table. If your other Northpass tables are syncing, the API key works and your Northpass plan likely does not include this endpoint. Ask Northpass support to enable it, then re-enable the sync. If every table is failing, check the key's permissions in your Northpass admin panel, then reconnect.",
+ # The quiz tables are built from the sent-webhooks log. A log with no quiz-completed
+ # event yields nothing on every run, and retrying cannot add a message to it.
+ QUIZ_LOG_EMPTY_MESSAGE: "Your Northpass sent-webhooks log holds no quiz-completed events, and the quiz_attempts and quiz_attempt_answers tables are built from that log. Subscribe a webhook endpoint to quiz-completed events in your Northpass admin panel, wait for a quiz completion, then re-enable the sync. The log keeps three months of messages.",
}
def get_schemas(
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 91507af4c781..6a45ebf3b66d 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
@@ -10,6 +10,7 @@ from parameterized import parameterized
from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.northpass_lms import (
+ NorthpassQuizLogEmptyError,
NorthpassResumeConfig,
_build_url,
_flatten_item,
@@ -18,6 +19,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_
_make_relationship_flattener,
northpass_source,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.settings import (
+ QUIZ_LOG_EMPTY_MESSAGE,
+)
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -233,6 +237,22 @@ class TestTopLevelPagination:
assert rows == []
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_page_stops_even_with_next_link(self, mock_make_session):
+ pages = {
+ COURSES_P1: _page([{"id": "1"}], next_url=COURSES_P2),
+ COURSES_P2: _page([], next_url="https://api.northpass.com/v2/courses?page=3&limit=100"),
+ }
+ sent = _wire(mock_make_session, pages)
+ manager = _make_manager()
+
+ rows = _rows("courses", manager)
+
+ assert [r["id"] for r in rows] == ["1"]
+ assert sent == [COURSES_P1, COURSES_P2]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [NorthpassResumeConfig(next_url=COURSES_P2)]
+
class TestFanOut:
def _parent_and_children(self) -> dict[str, Any]:
@@ -426,7 +446,7 @@ def _message_without_payload() -> dict[str, Any]:
class TestQuizAttemptFlattener:
def test_reshapes_webhook_message_into_attempt_row(self):
- row = _make_quiz_attempt_flattener()(_quiz_message("at1"))
+ row = _make_quiz_attempt_flattener(set())(_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
@@ -450,10 +470,10 @@ class TestQuizAttemptFlattener:
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) == []
+ assert _make_quiz_attempt_flattener(set())(message) == []
def test_dedupes_attempts_across_messages_within_a_run(self):
- flatten = _make_quiz_attempt_flattener()
+ flatten = _make_quiz_attempt_flattener(set())
first = flatten(_quiz_message("at1", message_id="m1"))
second = flatten(_quiz_message("at1", message_id="m2"))
@@ -466,11 +486,11 @@ class TestQuizAttemptFlattener:
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)
+ assert isinstance(_make_quiz_attempt_flattener(set())(_quiz_message("at1")), dict)
+ assert isinstance(_make_quiz_attempt_flattener(set())(_quiz_message("at1")), dict)
def test_missing_relationships_still_emit_id_columns(self):
- row = _make_quiz_attempt_flattener()(_quiz_message("at1", relationships={}))
+ row = _make_quiz_attempt_flattener(set())(_quiz_message("at1", relationships={}))
assert isinstance(row, dict)
# Columns must exist (as None) even when a reference is absent, so the table schema stays
@@ -545,6 +565,52 @@ class TestQuizAttemptsAndAnswers:
"https://api.northpass.com/v2/quiz_attempts/at2/answers?limit=100",
]
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_log_with_next_link_stops_and_raises(self, mock_make_session):
+ pages = {WEBHOOKS_URL: _page([], next_url="https://api.northpass.com/v2/webhooks?page=2&limit=50")}
+ sent = _wire(mock_make_session, pages)
+
+ with pytest.raises(NorthpassQuizLogEmptyError, match=QUIZ_LOG_EMPTY_MESSAGE):
+ _rows("quiz_attempts", _make_manager())
+
+ assert sent == [WEBHOOKS_URL]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_log_holding_only_other_event_types_raises(self, mock_make_session):
+ pages = {WEBHOOKS_URL: _page([_quiz_message("at9", message_id="m3", event_type="course_completed_events")])}
+ _wire(mock_make_session, pages)
+
+ with pytest.raises(NorthpassQuizLogEmptyError, match="quiz_attempts has no rows to sync"):
+ _rows("quiz_attempts", _make_manager())
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_answers_raise_when_the_log_holds_no_attempt(self, mock_make_session):
+ pages = {WEBHOOKS_URL: _page([])}
+ sent = _wire(mock_make_session, pages)
+
+ with pytest.raises(NorthpassQuizLogEmptyError, match="quiz_attempt_answers has no rows to sync"):
+ _rows("quiz_attempt_answers", _make_manager())
+
+ assert sent == [WEBHOOKS_URL]
+
+ @parameterized.expand(
+ [
+ ("empty_page", _page([])),
+ ("ignored_404", _resp({"errors": []}, status=404)),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_answers_yield_nothing_when_the_log_attempt_has_no_answers(
+ self, _name: str, answers: Response, mock_make_session: mock.MagicMock
+ ) -> None:
+ answers_url = "https://api.northpass.com/v2/quiz_attempts/at1/answers?limit=100"
+ sent = _wire(mock_make_session, {WEBHOOKS_URL: _page([_quiz_message("at1")]), answers_url: answers})
+
+ rows = _rows("quiz_attempt_answers", _make_manager())
+
+ assert rows == []
+ assert sent == [WEBHOOKS_URL, answers_url]
+
class TestNorthpassSource:
@parameterized.expand(
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 573d7af610ab..aa3dffb999f7 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
@@ -32,6 +32,10 @@ class TestNorthpassLMSSource:
[
("unauthorized", "401 Client Error: Unauthorized for url: https://api.northpass.com/v2/people?limit=100"),
("forbidden", "403 Client Error: Forbidden for url: https://api.northpass.com/v2/courses?limit=100"),
+ (
+ "empty_quiz_log",
+ "Northpass sent-webhooks log returned no quiz-completed events, so quiz_attempts has no rows to sync",
+ ),
]
)
def test_non_retryable_errors_match_auth_failures(self, _name, observed_error):