: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): migrate 5 sources to rest_source (batch 2) + json-body pagination (#71540)
Tom Owers9ec9b3ece1a4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.pyindex 4d4ebe1b927d..cca72355e9f1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py@@ -1,32 +1,29 @@import reimport dataclasses-from collections.abc import Iterator-from typing import Any+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 requests import Request, Response+from requests.auth import HTTPBasicAuth-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import (AGILECRM_ENDPOINTS,BASE_URL_TEMPLATE,)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,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginatorfrom 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# A valid Agile CRM subdomain is a single DNS label: letters, digits and hyphens only. Constraining# the domain to this pattern stops a malicious value (e.g. `evil.com#`) from retargeting the basic-auth# credentials at an attacker-controlled host once it's interpolated into the base URL._DOMAIN_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]*$")-REQUEST_TIMEOUT_SECONDS = 60---class AgileCRMRetryableError(Exception):- pass-@dataclasses.dataclassclass AgileCRMResumeConfig:@@ -46,104 +43,56 @@ def base_url(domain: str) -> str:return BASE_URL_TEMPLATE.format(domain=_validate_domain(domain))-def _make_session(email: str, api_key: str) -> requests.Session:- # Agile CRM authenticates with HTTP Basic: account email as username, API key as password.- session = make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key,))- session.auth = (email, api_key)- return session+class AgileCRMCursorPaginator(BasePaginator):+ """Agile CRM signals the next page via a `cursor` field on the *last* item of the current page.+ A missing cursor or a short page (fewer items than the requested page size) means the final page.+ The cursor is stripped from the yielded rows by the endpoint's `data_map`, not here.+ """-@retry(- retry=retry_if_exception_type((AgileCRMRetryableError, 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, url: str, params: dict[str, Any], logger: FilteringBoundLogger-) -> list[dict[str, Any]]:- response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)+ def __init__(self, page_size: int) -> None:+ super().__init__()+ self.page_size = page_size+ self._cursor: Optional[str] = None- if response.status_code == 429 or response.status_code >= 500:- raise AgileCRMRetryableError(f"Agile CRM API error (retryable): status={response.status_code}, url={url}")+ def _inject_cursor(self, request: Request) -> None:+ if self._cursor is not None:+ if request.params is None:+ request.params = {}+ request.params["cursor"] = self._cursor- if not response.ok:- logger.error(f"Agile CRM API error: status={response.status_code}, body={response.text}, url={url}")- response.raise_for_status()+ def init_request(self, request: Request) -> None:+ # Honour a seeded resume cursor on the first request.+ self._inject_cursor(request)- data = response.json()- # Known list endpoints return a bare JSON array. Tolerate an unexpected object by returning no rows- # rather than crashing the sync.- if isinstance(data, list):- return data- return []---def get_rows(- domain: str,- email: str,- api_key: str,- endpoint: str,- logger: FilteringBoundLogger,- resumable_source_manager: ResumableSourceManager[AgileCRMResumeConfig],-) -> Iterator[Any]:- config = AGILECRM_ENDPOINTS[endpoint]- url = f"{base_url(domain)}/{config.path}"- session = _make_session(email, api_key)- batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)-- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- cursor = resume.cursor if resume else None- if cursor:- logger.debug(f"Agile CRM: resuming {endpoint} from cursor={cursor}")-- while True:- params: dict[str, Any] = {"page_size": config.page_size}- if cursor:- params["cursor"] = cursor-- items = _fetch_page(session, url, params, logger)- if not items:- break-- # Agile CRM signals the next page via a `cursor` field on the *last* item of the current page.- last_item = items[-1]+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ items = data or []+ last_item = items[-1] if items else Nonenext_cursor = last_item.get("cursor") if isinstance(last_item, dict) else None- # The cursor is navigation metadata, not data. Strip it from the last item so it isn't written- # to the warehouse as a sparse `cursor` column that only the final row of each page carries.- if isinstance(last_item, dict) and "cursor" in last_item:- items = [*items[:-1], {k: v for k, v in last_item.items() if k != "cursor"}]+ self._cursor = next_cursor+ # No items, no cursor on the last item, or a short page all mean we've reached the end.+ self._has_next_page = bool(next_cursor) and len(items) >= self.page_size- for item in items:- batcher.batch(item)- if batcher.should_yield():- yield batcher.get_table()- # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary- # key) rather than skipping it. Only persist when another page follows.- if next_cursor:- resumable_source_manager.save_state(AgileCRMResumeConfig(cursor=next_cursor))+ def update_request(self, request: Request) -> None:+ self._inject_cursor(request)- # No cursor, or a short page, means we've reached the end.- if not next_cursor or len(items) < config.page_size:- break+ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page and self._cursor is not None:+ return {"cursor": self._cursor}+ return None- cursor = next_cursor+ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor is not None:+ self._cursor = cursor+ self._has_next_page = True- if batcher.should_yield(include_incomplete_chunk=True):- yield batcher.get_table()---def validate_credentials(domain: str, email: str, api_key: str) -> bool:- try:- url = f"{base_url(domain)}/contacts"- except ValueError:- return False- try:- response = _make_session(email, api_key).get(url, params={"page_size": 1}, timeout=REQUEST_TIMEOUT_SECONDS)- return response.status_code == 200- except Exception:- return False+def _strip_cursor(item: dict[str, Any]) -> dict[str, Any]:+ # The cursor is navigation metadata carried on the last item of each page, not data. Strip it so+ # it isn't written to the warehouse as a sparse `cursor` column that only the final row of each+ # page carries.+ return {k: v for k, v in item.items() if k != "cursor"}def agilecrm_source(@@ -151,20 +100,75 @@ def agilecrm_source(email: str,api_key: str,endpoint: str,- logger: FilteringBoundLogger,+ team_id: int,+ job_id: str,resumable_source_manager: ResumableSourceManager[AgileCRMResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:- endpoint_config = AGILECRM_ENDPOINTS[endpoint]+ config = AGILECRM_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": base_url(domain),+ "headers": {"Accept": "application/json"},+ # Agile CRM authenticates with HTTP Basic: account email as username, API key as password.+ "auth": {"type": "http_basic", "username": email, "password": api_key},+ "paginator": AgileCRMCursorPaginator(page_size=config.page_size),+ },+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": {"page_size": config.page_size},+ "data_selector": config.data_selector,+ # Known list endpoints return a bare JSON array; a 200 object body means the+ # response shape changed — fail loud instead of silently mis-syncing.+ "data_selector_required": True,+ },+ "data_map": _strip_cursor,+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.cursor:+ initial_paginator_state = {"cursor": resume.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; saved AFTER a page is yielded so a crash re-yields+ # the last page (merge dedupes on the primary key) rather than skipping it.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(AgileCRMResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )return SourceResponse(name=endpoint,- items=lambda: get_rows(- domain=domain,- email=email,- api_key=api_key,- endpoint=endpoint,- logger=logger,- resumable_source_manager=resumable_source_manager,- ),- primary_keys=endpoint_config.primary_keys,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ )+++def validate_credentials(domain: str, email: str, api_key: str) -> bool:+ try:+ url = f"{base_url(domain)}/contacts"+ except ValueError:+ return False++ ok, _status = validate_via_probe(+ lambda: make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key,)),+ f"{url}?page_size=1",+ auth=HTTPBasicAuth(email, api_key),)+ return okdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.pyindex 54da9e734a73..5a3551239e36 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/source.py@@ -25,7 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom 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.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AgileCRMSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -118,19 +121,7 @@ Your domain is the subdomain of your Agile CRM URL — for `https://acme.agilecr) -> list[SourceSchema]:# Agile CRM documents no server-side updated-since/created-after filter on any list endpoint,# so every table is full refresh only.- 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+ return build_endpoint_schemas(ENDPOINTS, {}, names)def validate_credentials(self, config: AgileCRMSourceConfig, team_id: int, schema_name: Optional[str] = None@@ -154,6 +145,8 @@ Your domain is the subdomain of your Agile CRM URL — for `https://acme.agilecremail=config.email,api_key=config.api_key,endpoint=inputs.schema_name,- logger=inputs.logger,+ team_id=inputs.team_id,+ job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=None, # every Agile CRM endpoint is full refresh)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.pyindex 6f9d026f65a2..bdc278ab52fe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py@@ -1,64 +1,77 @@+import jsonfrom typing import Anyimport pytest-from unittest.mock import MagicMock, patch+from unittest import mock-import requestsfrom parameterized import parameterized+from requests import Response-from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm import agilecrmfrom products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.agilecrm import (AgileCRMResumeConfig,+ agilecrm_source,base_url,- get_rows,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import AGILECRM_ENDPOINTS+# 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"+# validate_credentials builds its own tracked session in the agilecrm module.+AGILECRM_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.agilecrm.make_tracked_session"+)++PAGE_SIZE = AGILECRM_ENDPOINTS["contacts"].page_size+++def _response(body: Any) -> Response:+ # Agile CRM list endpoints return a bare JSON array as the body.+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: AgileCRMResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager-class _FakeResumableManager:- def __init__(self, state: AgileCRMResumeConfig | None = None) -> None:- self._state = state- self.saved: list[AgileCRMResumeConfig] = []- def can_resume(self) -> bool:- return self._state is not None+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request's params AT SEND TIME.- def load_state(self) -> AgileCRMResumeConfig | None:- return self._state+ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the run+ shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []- def save_state(self, data: AgileCRMResumeConfig) -> None:- self.saved.append(data)+ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ return mock.MagicMock()+ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots-def _collect_rows(- monkeypatch: Any,- pages: list[list[dict[str, Any]]],- manager: _FakeResumableManager,- endpoint: str = "contacts",-) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:- """Drive get_rows against a queue of fake pages, returning (rows, recorded request params)."""- recorded_params: list[dict[str, Any]] = []- queue = list(pages)- def fake_fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> list[dict[str, Any]]:- recorded_params.append(dict(params))- return queue.pop(0) if queue else []+def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]- monkeypatch.setattr(agilecrm, "_fetch_page", fake_fetch)- monkeypatch.setattr(agilecrm, "_make_session", lambda email, api_key: MagicMock())- rows: list[dict[str, Any]] = []- for table in get_rows(+def _source(manager: mock.MagicMock, endpoint: str = "contacts"):+ return agilecrm_source(domain="acme",email="[email protected]",api_key="key",endpoint=endpoint,- logger=MagicMock(),- resumable_source_manager=manager, # type: ignore[arg-type]- ):- rows.extend(table.to_pylist())- return rows, recorded_params+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )class TestBaseUrl:@@ -89,81 +102,103 @@ class TestBaseUrl:class TestPagination:- def test_paginates_until_short_page(self, monkeypatch: Any) -> None:- page_size = AGILECRM_ENDPOINTS["contacts"].page_size- first_page = [{"id": i} for i in range(page_size - 1)] + [{"id": page_size, "cursor": "CURSOR1"}]+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_short_page(self, MockSession) -> None:+ session = MockSession.return_value+ first_page = [{"id": i} for i in range(PAGE_SIZE - 1)] + [{"id": PAGE_SIZE, "cursor": "CURSOR1"}]second_page = [{"id": 9001}] # short page -> terminal- manager = _FakeResumableManager()+ params = _wire(session, [_response(first_page), _response(second_page)])- rows, params = _collect_rows(monkeypatch, [first_page, second_page], manager)+ manager = _make_manager()+ rows = _rows(_source(manager))- assert len(rows) == page_size + 1+ assert len(rows) == PAGE_SIZE + 1# First request has no cursor; the second carries the cursor from the last item of page one.assert "cursor" not in params[0]+ assert params[0]["page_size"] == PAGE_SIZEassert params[1]["cursor"] == "CURSOR1"# The cursor is navigation metadata and must never leak into the warehouse rows.assert all("cursor" not in row for row in rows)+ # Checkpoint saved after the first page (points at the next page); the short page ends it.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == AgileCRMResumeConfig(cursor="CURSOR1")- def test_stops_when_full_page_has_no_cursor(self, monkeypatch: Any) -> None:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_when_full_page_has_no_cursor(self, MockSession) -> None:# A full page whose last item carries no cursor must terminate rather than loop forever.- page_size = AGILECRM_ENDPOINTS["contacts"].page_size- full_page_no_cursor = [{"id": i} for i in range(page_size)]- manager = _FakeResumableManager()+ session = MockSession.return_value+ full_page_no_cursor = [{"id": i} for i in range(PAGE_SIZE)]+ _wire(session, [_response(full_page_no_cursor), _response([{"id": 1}])])++ manager = _make_manager()+ rows = _rows(_source(manager))++ assert len(rows) == PAGE_SIZE+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()- rows, params = _collect_rows(monkeypatch, [full_page_no_cursor, [{"id": 1}]], manager)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_on_short_page_even_with_cursor(self, MockSession) -> None:+ # A short page is terminal even if its last item still carries a cursor.+ session = MockSession.return_value+ short_page = [{"id": 1}, {"id": 2, "cursor": "DANGLING"}]+ _wire(session, [_response(short_page), _response([{"id": 3}])])- assert len(rows) == page_size- assert len(params) == 1+ manager = _make_manager()+ rows = _rows(_source(manager))++ assert [r["id"] for r in rows] == [1, 2]+ assert session.send.call_count == 1+ assert all("cursor" not in row for row in rows)+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_first_page_yields_nothing(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([])])++ manager = _make_manager()+ rows = _rows(_source(manager))- def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:- manager = _FakeResumableManager()- rows, params = _collect_rows(monkeypatch, [[]], manager)assert rows == []- assert len(params) == 1+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_uses_saved_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}])])- def test_resume_uses_saved_cursor(self, monkeypatch: Any) -> None:- manager = _FakeResumableManager(AgileCRMResumeConfig(cursor="SAVED"))- rows, params = _collect_rows(monkeypatch, [[{"id": 1}]], manager)+ manager = _make_manager(AgileCRMResumeConfig(cursor="SAVED"))+ rows = _rows(_source(manager))assert rows == [{"id": 1}]assert params[0]["cursor"] == "SAVED"- def test_saves_state_after_yielding_batch(self, monkeypatch: Any) -> None:- # The Batcher flushes once 2000 rows accumulate; state must be saved (with the next cursor)- # only after that batch is yielded, so a crash re-yields the last page rather than skipping it.- big_first_page = [{"id": i} for i in range(2499)] + [{"id": 2500, "cursor": "NEXT"}]- manager = _FakeResumableManager()+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_non_list_body_raises_loudly(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"error": "something went wrong"})])- rows, _ = _collect_rows(monkeypatch, [big_first_page, [{"id": 1}]], manager)-- assert manager.saved- assert manager.saved[0].cursor == "NEXT"- # The cursor is navigation metadata and must never leak into the warehouse rows.- assert all("cursor" not in row for row in rows)+ # A 200 object body means the response shape changed — fail loud, not silently mis-sync.+ with pytest.raises(ValueError, match="Required a list response body"):+ _rows(_source(_make_manager()))class TestValidateCredentials:@parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:- response = MagicMock()- response.status_code = status_code- session = MagicMock()- session.get.return_value = response-- with patch.object(agilecrm, "_make_session", lambda email, api_key: session):+ with mock.patch(AGILECRM_SESSION_PATCH) as mock_session:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)assert validate_credentials("acme", "[email protected]", "key") is expected- def test_invalid_domain_short_circuits_to_false(self, monkeypatch: Any) -> None:+ def test_invalid_domain_short_circuits_to_false(self) -> None:# An invalid domain must fail before any request is attempted.- session = MagicMock()- monkeypatch.setattr(agilecrm, "_make_session", lambda email, api_key: session)-- assert validate_credentials("evil.com#", "[email protected]", "key") is False- session.get.assert_not_called()-- def test_network_error_is_false(self, monkeypatch: Any) -> None:- session = MagicMock()- session.get.side_effect = requests.ConnectionError("boom")- monkeypatch.setattr(agilecrm, "_make_session", lambda email, api_key: session)-- assert validate_credentials("acme", "[email protected]", "key") is False+ with mock.patch(AGILECRM_SESSION_PATCH) as mock_session:+ assert validate_credentials("evil.com#", "[email protected]", "key") is False+ mock_session.assert_not_called()++ def test_network_error_is_false(self) -> None:+ with mock.patch(AGILECRM_SESSION_PATCH) as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("acme", "[email protected]", "key") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/aha.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/aha.pyindex e126ed7a0096..aa82e6cf4c62 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/aha.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/aha.py@@ -1,15 +1,10 @@import reimport dataclasses-from collections.abc import Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional-from urllib.parse import urlencode-import requests-from structlog.types import FilteringBoundLogger-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from requests import Response-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import (AHA_ENDPOINTS,@@ -17,7 +12,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settinAhaEndpointConfig,)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,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.jsonpath_utils import (+ find_values,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)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_probeAHA_API_PATH = "/api/v1"@@ -26,10 +32,6 @@ AHA_API_PATH = "/api/v1"_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")-class AhaRetryableError(Exception):- pass--@dataclasses.dataclassclass AhaResumeConfig:# Next 1-indexed page to fetch. None means "start from page 1".@@ -58,10 +60,6 @@ def _base_url(subdomain: str) -> str:return f"https://{normalize_subdomain(subdomain)}.aha.io{AHA_API_PATH}"-def _headers(api_key: str) -> dict[str, str]:- return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}--def _format_updated_since(value: Any) -> str:"""Format an incremental cursor as the ISO8601 UTC string Aha! expects for `updated_since`."""if isinstance(value, datetime):@@ -72,12 +70,6 @@ def _format_updated_since(value: Any) -> str:return str(value)-def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:- if not params:- return f"{base_url}{path}"- return f"{base_url}{path}?{urlencode(params)}"--def _build_initial_params(config: AhaEndpointConfig,should_use_incremental_field: bool,@@ -90,117 +82,99 @@ def _build_initial_params(return params-@retry(- retry=retry_if_exception_type((AhaRetryableError, 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, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:- response = session.get(url, headers=headers, timeout=60)-- # Aha! enforces 300 req/min and 20 req/sec; 429 carries reset headers. Back off and retry rather- # than failing the sync. Transient 5xx are retryable too.- if response.status_code == 429 or response.status_code >= 500:- raise AhaRetryableError(f"Aha! API error (retryable): status={response.status_code}, url={url}")-- if not response.ok:- logger.error(f"Aha! API error: status={response.status_code}, body={response.text}, url={url}")- response.raise_for_status()-- return response.json()+class AhaPageNumberPaginator(PageNumberPaginator):+ """Page-number pagination with Aha!'s full-page fallback.--def _has_more_pages(pagination: dict[str, Any], page: int, item_count: int) -> bool:- """Decide whether to fetch another page.-- Prefer Aha!'s `pagination.total_pages`; fall back to a full-page heuristic if the metadata is- ever absent (a full page implies there may be more).+ Aha! reports `pagination.total_pages` (total number of PAGES), which the base paginator uses+ to stop after the last page. If that metadata is ever absent, fall back to the full-page+ heuristic: a short page means there are no more pages."""- total_pages = pagination.get("total_pages")- if isinstance(total_pages, int):- return page < total_pages- return item_count >= PER_PAGE---def get_rows(- subdomain: str,- api_key: str,- endpoint: str,- logger: FilteringBoundLogger,- resumable_source_manager: ResumableSourceManager[AhaResumeConfig],- should_use_incremental_field: bool = False,- db_incremental_field_last_value: Any = None,- incremental_field: str | None = None,-) -> Iterator[Any]:- config = AHA_ENDPOINTS[endpoint]- base_url = _base_url(subdomain)- headers = _headers(api_key)- batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)- session = make_tracked_session()-- params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)-- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- page = resume.next_page if resume is not None and resume.next_page else 1- if page > 1:- logger.debug(f"Aha!: resuming {endpoint} from page {page}")- while True:- data = _fetch_page(session, _build_url(base_url, config.path, {**params, "page": page}), headers, logger)- items = data.get(config.response_key, [])- if not items:- break-- has_more = _has_more_pages(data.get("pagination", {}), page, len(items))-- for item in items:- batcher.batch(item)- if batcher.should_yield():- yield batcher.get_table()- # Save AFTER yielding so a crash re-yields the last page rather than skipping it —- # merge dedupes on the primary key.- if has_more:- resumable_source_manager.save_state(AhaResumeConfig(next_page=page + 1))-- if not has_more:- break- page += 1-- if batcher.should_yield(include_incomplete_chunk=True):- yield batcher.get_table()+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if not self._has_next_page or data is None:+ return+ try:+ values = find_values(self.total_path, response.json()) if self.total_path else []+ except Exception:+ values = []+ has_total_metadata = bool(values) and isinstance(values[0], int)+ if not has_total_metadata and len(data) < PER_PAGE:+ self._has_next_page = Falsedef aha_source(subdomain: str,api_key: str,endpoint: str,- logger: FilteringBoundLogger,+ team_id: int,+ job_id: str,resumable_source_manager: ResumableSourceManager[AhaResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,- incremental_field: str | None = None,) -> SourceResponse:config = AHA_ENDPOINTS[endpoint]+ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": _base_url(subdomain),+ # Auth (Bearer) goes through the framework auth config so its value is redacted from+ # logs; only the non-secret accept header is set here.+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ "paginator": AhaPageNumberPaginator(+ base_page=1,+ page_param="page",+ total_path="pagination.total_pages",+ ),+ },+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ # A 200 body without the root key yields an empty page and ends pagination —+ # same as the old implementation's `data.get(key, []) -> stop`.+ "data_selector": config.response_key,+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_page:+ initial_paginator_state = {"page": resume.next_page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields+ # the last page (merge dedupes) rather than skipping it.+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(AhaResumeConfig(next_page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )return SourceResponse(name=endpoint,- items=lambda: get_rows(- subdomain=subdomain,- api_key=api_key,- endpoint=endpoint,- logger=logger,- resumable_source_manager=resumable_source_manager,- should_use_incremental_field=should_use_incremental_field,- db_incremental_field_last_value=db_incremental_field_last_value,- incremental_field=incremental_field,- ),+ items=lambda: resource,primary_keys=config.primary_keys,partition_count=1,partition_size=1,partition_mode="datetime" if config.partition_key else None,partition_format="month" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=resource.column_hints,)@@ -210,9 +184,9 @@ def validate_credentials(subdomain: str, api_key: str) -> tuple[bool, int | NoneReturns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises``ValueError`` if the subdomain is malformed so the caller can surface a precise message."""- url = _build_url(_base_url(subdomain), "/me", {})- try:- response = make_tracked_session().get(url, headers=_headers(api_key), timeout=10)- except Exception:- return False, None- return response.status_code == 200, response.status_code+ url = f"{_base_url(subdomain)}/me"+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ url,+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.pyindex d12df678f3f0..2fd7bc3b6e51 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.py@@ -18,18 +18,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aha.aha imaha_source,validate_credentials as validate_aha_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import (- AHA_ENDPOINTS,- ENDPOINTS,- INCREMENTAL_FIELDS,-)+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom 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 SourceRegistryfrom 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.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AhaSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -95,7 +94,7 @@ Create an API key under **Settings → Personal → Developer → API keys** indef get_non_retryable_errors(self) -> dict[str, str | None]:return {- # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # 401/403 surface as a requests HTTPError when the REST client calls `raise_for_status()`.# Retrying can never fix a credential/permission problem, so fail the sync. Match the# stable status text and `.aha.io` host, not the per-request path."401 Client Error: Unauthorized": "Your Aha! API key is invalid or has been revoked. Create a new key in your Aha! account settings, then reconnect.",@@ -110,21 +109,10 @@ Create an API key under **Settings → Personal → Developer → API keys** innames: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- def _build_schema(endpoint: str) -> SourceSchema:- endpoint_config = AHA_ENDPOINTS[endpoint]- return SourceSchema(- name=endpoint,- supports_incremental=endpoint_config.supports_incremental,- supports_append=endpoint_config.supports_incremental,- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- should_sync_default=endpoint_config.should_sync_default,- )-- schemas = [_build_schema(endpoint) 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+ # `build_endpoint_schemas` treats any endpoint present in the mapping as incremental, so+ # drop the full-refresh endpoints (empty `incremental_fields`) to keep them full refresh.+ incremental_fields = {name: fields for name, fields in INCREMENTAL_FIELDS.items() if fields}+ return build_endpoint_schemas(ENDPOINTS, incremental_fields, names)def validate_credentials(self, config: AhaSourceConfig, team_id: int, schema_name: Optional[str] = None@@ -153,11 +141,11 @@ Create an API key under **Settings → Personal → Developer → API keys** insubdomain=config.subdomain,api_key=config.api_key,endpoint=inputs.schema_name,- logger=inputs.logger,+ team_id=inputs.team_id,+ job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,should_use_incremental_field=inputs.should_use_incremental_field,db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,- incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.pyindex b12efe036c91..569232fb4ecf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py@@ -1,23 +1,28 @@+import jsonfrom datetime import UTC, date, datetimefrom typing import Anyimport pytest-from unittest.mock import MagicMock+from unittest import mockfrom parameterized import parameterized+from requests import Response-from products.warehouse_sources.backend.temporal.data_imports.sources.aha import ahafrom products.warehouse_sources.backend.temporal.data_imports.sources.aha.aha import (- PER_PAGE,AhaResumeConfig,_build_initial_params,- _build_url,_format_updated_since,- _has_more_pages,- get_rows,+ aha_source,normalize_subdomain,+ validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import AHA_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import AHA_ENDPOINTS, PER_PAGE+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth++# 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"+# validate_credentials builds its own tracked session in the aha module.+AHA_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.aha.aha.make_tracked_session"class TestNormalizeSubdomain:@@ -89,176 +94,228 @@ class TestBuildInitialParams:assert params == {"per_page": PER_PAGE}-class TestBuildUrl:- def test_no_params(self) -> None:- assert _build_url("https://acme.aha.io/api/v1", "/me", {}) == "https://acme.aha.io/api/v1/me"-- def test_encodes_params(self) -> None:- url = _build_url(- "https://acme.aha.io/api/v1", "/features", {"page": 2, "updated_since": "2026-03-04T02:58:14Z"}- )- assert url == "https://acme.aha.io/api/v1/features?page=2&updated_since=2026-03-04T02%3A58%3A14Z"---class TestHasMorePages:- @parameterized.expand(- [- ("more_pages", {"current_page": 1, "total_pages": 3}, 1, 200, True),- ("last_page", {"current_page": 3, "total_pages": 3}, 3, 50, False),- ("missing_meta_full_page", {}, 1, PER_PAGE, True),- ("missing_meta_partial_page", {}, 1, 5, False),- ]+def _response(+ response_key: str,+ items: list[dict[str, Any]] | None,+ *,+ current_page: int | None = None,+ total_pages: int | None = None,+ drop_key: bool = False,+) -> Response:+ body: dict[str, Any] = {}+ if not drop_key:+ body[response_key] = items or []+ if total_pages is not None:+ body["pagination"] = {"current_page": current_page or 1, "total_pages": total_pages}+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: AhaResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request AT SEND TIME.++ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the+ run shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return aha_source(+ subdomain="acme",+ api_key="key",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,)- def test_has_more(self, _name: str, pagination: dict, page: int, item_count: int, expected: bool) -> None:- assert _has_more_pages(pagination, page, item_count) is expected---class _FakeResumableManager:- def __init__(self, state: AhaResumeConfig | None = None) -> None:- self._state = state- self.saved: list[AhaResumeConfig] = []- def can_resume(self) -> bool:- return self._state is not None- def load_state(self) -> AhaResumeConfig | None:- return self._state+def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]- def save_state(self, data: AhaResumeConfig) -> None:- self.saved.append(data)+class TestAhaSource:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_total_pages(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response("features", [{"id": "1"}, {"id": "2"}], current_page=1, total_pages=2),+ _response("features", [{"id": "3"}], current_page=2, total_pages=2),+ ],+ )-class _FakeBatcher:- """Yields one batch per item so save-after-yield behavior is observable without 2000+ rows."""+ rows = _rows(_source("features", _make_manager()))- def __init__(self, *args: Any, **kwargs: Any) -> None:- self._rows: list[dict] = []+ assert [r["id"] for r in rows] == ["1", "2", "3"]+ # total_pages=2 terminates after the last page — no extra empty-page request.+ assert session.send.call_count == 2+ assert snapshots[0]["url"] == "https://acme.aha.io/api/v1/features"+ assert snapshots[0]["params"] == {"per_page": PER_PAGE, "page": 1}+ assert snapshots[1]["params"] == {"per_page": PER_PAGE, "page": 2}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_auth_is_framework_bearer(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("features", [{"id": "1"}], total_pages=1)])++ _rows(_source("features", _make_manager()))++ auth = snapshots[0]["auth"]+ assert isinstance(auth, BearerTokenAuth)+ assert auth.token == "key"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response("features", [{"id": "1"}], current_page=1, total_pages=2),+ _response("features", [{"id": "2"}], current_page=2, total_pages=2),+ ],+ )- def batch(self, row: dict) -> None:- self._rows.append(row)+ manager = _make_manager()+ _rows(_source("features", manager))- def should_yield(self, include_incomplete_chunk: bool = False) -> bool:- return len(self._rows) > 0+ # State is saved only while more pages remain (page 1 -> next_page 2), never on the last page.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == AhaResumeConfig(next_page=2)- def get_table(self) -> list[dict]:- rows = self._rows- self._rows = []- return rows+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_page(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("features", [{"id": "2"}], current_page=2, total_pages=2)])+ rows = _rows(_source("features", _make_manager(AhaResumeConfig(next_page=2))))-def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:- fetched: list[str] = []+ assert [r["id"] for r in rows] == ["2"]+ assert session.send.call_count == 1+ assert snapshots[0]["params"]["page"] == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_cursor_added_to_request(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("features", [{"id": "1"}], total_pages=1)])++ _rows(+ _source(+ "features",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ )- def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:- fetched.append(url)- return pages[url]+ assert snapshots[0]["params"]["updated_since"] == "2026-03-04T02:58:14Z"- monkeypatch.setattr(aha, "_fetch_page", fake_fetch)- return fetched+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_uses_response_key_for_todos(self, MockSession) -> None:+ # to-dos live at /tasks with a `tasks` root key.+ session = MockSession.return_value+ snapshots = _wire(session, [_response("tasks", [{"id": "t1"}], total_pages=1)])+ rows = _rows(_source("todos", _make_manager()))-def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:- monkeypatch.setattr(aha, "Batcher", _FakeBatcher)- rows: list[dict] = []- for batch in get_rows(- subdomain="acme",- api_key="key",- logger=MagicMock(),- resumable_source_manager=manager, # type: ignore[arg-type]- **kwargs,- ):- rows.extend(batch)- return rows---class TestGetRows:- def test_paginates_until_last_page(self, monkeypatch: Any) -> None:- pages = {- "https://acme.aha.io/api/v1/features?per_page=200&page=1": {- "features": [{"id": "1"}, {"id": "2"}],- "pagination": {"current_page": 1, "total_pages": 2},- },- "https://acme.aha.io/api/v1/features?per_page=200&page=2": {- "features": [{"id": "3"}],- "pagination": {"current_page": 2, "total_pages": 2},- },- }- fetched = _patch_fetch(monkeypatch, pages)- rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="features")+ assert [r["id"] for r in rows] == ["t1"]+ assert snapshots[0]["url"] == "https://acme.aha.io/api/v1/tasks"- assert [r["id"] for r in rows] == ["1", "2", "3"]- assert fetched == list(pages)-- def test_saves_resume_state_after_each_yielded_page(self, monkeypatch: Any) -> None:- pages = {- "https://acme.aha.io/api/v1/features?per_page=200&page=1": {- "features": [{"id": "1"}],- "pagination": {"current_page": 1, "total_pages": 2},- },- "https://acme.aha.io/api/v1/features?per_page=200&page=2": {- "features": [{"id": "2"}],- "pagination": {"current_page": 2, "total_pages": 2},- },- }- _patch_fetch(monkeypatch, pages)- manager = _FakeResumableManager()- _collect(monkeypatch, manager, endpoint="features")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_on_empty_page(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response("goals", [], total_pages=1)])- # State is saved only while more pages remain (page 1 -> next_page 2), never on the last page.- assert manager.saved == [AhaResumeConfig(next_page=2)]-- def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:- pages = {- "https://acme.aha.io/api/v1/features?per_page=200&page=2": {- "features": [{"id": "2"}],- "pagination": {"current_page": 2, "total_pages": 2},- },- }- fetched = _patch_fetch(monkeypatch, pages)- rows = _collect(monkeypatch, _FakeResumableManager(AhaResumeConfig(next_page=2)), endpoint="features")+ manager = _make_manager()+ rows = _rows(_source("goals", manager))- assert [r["id"] for r in rows] == ["2"]- assert fetched == ["https://acme.aha.io/api/v1/features?per_page=200&page=2"]-- def test_incremental_cursor_added_to_request(self, monkeypatch: Any) -> None:- pages = {- "https://acme.aha.io/api/v1/features?per_page=200&updated_since=2026-03-04T02%3A58%3A14Z&page=1": {- "features": [{"id": "1"}],- "pagination": {"current_page": 1, "total_pages": 1},- },- }- fetched = _patch_fetch(monkeypatch, pages)- _collect(- monkeypatch,- _FakeResumableManager(),- endpoint="features",- should_use_incremental_field=True,- db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),- )- assert "updated_since=2026-03-04T02%3A58%3A14Z" in fetched[0]+ assert rows == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()- def test_uses_response_key_for_todos(self, monkeypatch: Any) -> None:- # to-dos live at /tasks with a `tasks` root key.- pages = {- "https://acme.aha.io/api/v1/tasks?per_page=200&page=1": {- "tasks": [{"id": "t1"}],- "pagination": {"current_page": 1, "total_pages": 1},- },- }- fetched = _patch_fetch(monkeypatch, pages)- rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="todos")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_response_key_stops_quietly(self, MockSession) -> None:+ # A body without the root key is treated as an empty page (old `data.get(key, []) -> stop`).+ session = MockSession.return_value+ _wire(session, [_response("goals", None, drop_key=True)])- assert [r["id"] for r in rows] == ["t1"]- assert fetched == ["https://acme.aha.io/api/v1/tasks?per_page=200&page=1"]-- def test_stops_on_empty_page(self, monkeypatch: Any) -> None:- pages = {- "https://acme.aha.io/api/v1/goals?per_page=200&page=1": {- "goals": [],- "pagination": {"current_page": 1, "total_pages": 1},- },- }- _patch_fetch(monkeypatch, pages)- rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="goals")+ rows = _rows(_source("goals", _make_manager()))assert rows == []+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_metadata_partial_page_stops(self, MockSession) -> None:+ # No pagination metadata + a short page -> no more pages (full-page fallback heuristic).+ session = MockSession.return_value+ _wire(session, [_response("features", [{"id": "1"}, {"id": "2"}])])++ rows = _rows(_source("features", _make_manager()))++ assert [r["id"] for r in rows] == ["1", "2"]+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_metadata_full_page_continues(self, MockSession) -> None:+ # No pagination metadata + a full page -> there may be more pages.+ session = MockSession.return_value+ full_page = [{"id": str(i)} for i in range(PER_PAGE)]+ _wire(session, [_response("features", full_page), _response("features", [{"id": "last"}])])++ rows = _rows(_source("features", _make_manager()))++ assert len(rows) == PER_PAGE + 1+ assert session.send.call_count == 2+++class TestValidateCredentials:+ @mock.patch(AHA_SESSION_PATCH)+ def test_ok(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert validate_credentials("acme", "key") == (True, 200)++ @mock.patch(AHA_SESSION_PATCH)+ def test_unauthorized(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)+ assert validate_credentials("acme", "key") == (False, 401)++ @mock.patch(AHA_SESSION_PATCH)+ def test_swallows_transport_errors(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("acme", "key") == (False, None)++ @mock.patch(AHA_SESSION_PATCH)+ def test_probes_me_endpoint_with_bearer_header(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("acme", "key")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://acme.aha.io/api/v1/me"+ assert call.kwargs["headers"]["Authorization"] == "Bearer key"++ @mock.patch(AHA_SESSION_PATCH)+ def test_bad_subdomain_raises_before_probe(self, mock_session) -> None:+ with pytest.raises(ValueError, match="Invalid Aha! account domain"):+ validate_credentials("acme/../evil", "key")+ mock_session.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.pyindex f1e3d232e1b9..20624e39bd92 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.py@@ -1,14 +1,11 @@import reimport dataclasses-from collections.abc import Iterator-from typing import Any+from typing import Any, Optional, castfrom urllib.parse import quoteimport requests-from structlog.types import FilteringBoundLogger-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from requests import Response-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.algolia.settings import (ALGOLIA_ENDPOINTS,@@ -16,6 +13,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.sePaginationStyle,)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,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ HTTPMethodBasic,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager# Algolia's REST API is served per-application. The main host handles both reads and the@@ -47,10 +57,6 @@ class AlgoliaResumeConfig:page: int | None = None-class AlgoliaRetryableError(Exception):- pass--def _base_url(application_id: str) -> str:if not _APPLICATION_ID_RE.match(application_id):raise InvalidApplicationIdError("Algolia Application ID must be alphanumeric (letters and digits only)")@@ -66,141 +72,137 @@ def _get_headers(application_id: str, api_key: str) -> dict[str, str]:}-def _endpoint_url(application_id: str, config: AlgoliaEndpointConfig, index_name: str | None) -> str:+def _endpoint_path(config: AlgoliaEndpointConfig, index_name: str | None) -> str:path = config.pathif config.requires_index:if not index_name:raise ValueError(f"Algolia endpoint '{config.name}' requires an index name")path = path.format(index=quote(index_name, safe=""))- return f"{_base_url(application_id)}{path}"+ return path-@retry(- retry=retry_if_exception_type((AlgoliaRetryableError, requests.ReadTimeout, requests.ConnectionError)),- stop=stop_after_attempt(5),- wait=wait_exponential_jitter(initial=1, max=30),- reraise=True,-)-def _fetch(- session: requests.Session,- method: str,- url: str,- headers: dict[str, str],- logger: FilteringBoundLogger,- params: dict[str, Any] | None = None,- body: dict[str, Any] | None = None,-) -> dict:- response = session.request(method, url, headers=headers, params=params, json=body, timeout=60)-- # Algolia rate-limits the API and surfaces transient errors as 429 / 5xx; retry those.- if response.status_code == 429 or response.status_code >= 500:- raise AlgoliaRetryableError(f"Algolia API error (retryable): status={response.status_code}, url={url}")-- if not response.ok:- logger.error(f"Algolia API error: status={response.status_code}, body={response.text}, url={url}")- response.raise_for_status()-- return response.json()---def _iter_cursor(- session: requests.Session,- url: str,- headers: dict[str, str],- config: AlgoliaEndpointConfig,- logger: FilteringBoundLogger,- batcher: Batcher,- manager: ResumableSourceManager[AlgoliaResumeConfig],- resume: AlgoliaResumeConfig | None,-) -> Iterator[Any]:- """Page the browse endpoint via its opaque cursor; a missing cursor signals end of index."""- cursor = resume.cursor if resume else None- while True:- body: dict[str, Any] = {"hitsPerPage": config.page_size}- if cursor:- body["cursor"] = cursor- data = _fetch(session, "POST", url, headers, logger, body=body)-- next_cursor = data.get("cursor")- for item in data.get(config.data_selector, []):- batcher.batch(item)- if batcher.should_yield():- yield batcher.get_table()- # Save after yielding so a crash re-yields the last batch (merge dedupes on- # the primary key) rather than skipping it.- if next_cursor:- manager.save_state(AlgoliaResumeConfig(cursor=next_cursor))-- if not next_cursor:- break- cursor = next_cursor- manager.save_state(AlgoliaResumeConfig(cursor=cursor))---def _iter_pages(- session: requests.Session,- url: str,- headers: dict[str, str],- config: AlgoliaEndpointConfig,- logger: FilteringBoundLogger,- batcher: Batcher,- manager: ResumableSourceManager[AlgoliaResumeConfig],- resume: AlgoliaResumeConfig | None,-) -> Iterator[Any]:- """Page the search (synonyms/rules) and list (indices) endpoints via 0-based page numbers."""- page = resume.page if resume and resume.page is not None else 0- while True:- if config.method == "POST":- data = _fetch(session, "POST", url, headers, logger, body={"page": page, "hitsPerPage": config.page_size})- else:- data = _fetch(session, "GET", url, headers, logger, params={"page": page, "hitsPerPage": config.page_size})-- items = data.get(config.data_selector, [])- next_page = page + 1- for item in items:- batcher.batch(item)- if batcher.should_yield():- yield batcher.get_table()- manager.save_state(AlgoliaResumeConfig(page=next_page))-- if not items:- break- # `indices` reports the page count directly; the search endpoints don't, so fall back to- # a short final page (fewer rows than requested) to detect the end.- nb_pages = data.get("nbPages")- if nb_pages is not None:- if next_page >= nb_pages:- break- elif len(items) < config.page_size:- break-- page = next_page- manager.save_state(AlgoliaResumeConfig(page=page))---def get_rows(+def _endpoint_url(application_id: str, config: AlgoliaEndpointConfig, index_name: str | None) -> str:+ return f"{_base_url(application_id)}{_endpoint_path(config, index_name)}"+++class AlgoliaPageNumberPaginator(PageNumberPaginator):+ """Page-number paginator matching Algolia's mixed termination rules.++ `GET /1/indexes` reports the page count directly (`nbPages`, handled via `total_path`); the+ synonyms/rules search endpoints don't, so when `nbPages` is absent a short final page (fewer+ rows than requested) signals the end without paying an extra empty-page request.+ """++ def __init__(self, page_size: int, **kwargs: Any) -> None:+ super().__init__(total_path="nbPages", **kwargs)+ self.page_size = page_size++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if not self._has_next_page:+ return+ try:+ body = response.json()+ nb_pages = body.get("nbPages") if isinstance(body, dict) else None+ except Exception:+ nb_pages = None+ if nb_pages is None and data is not None and len(data) < self.page_size:+ self._has_next_page = False+++def _build_paginator(config: AlgoliaEndpointConfig) -> BasePaginator:+ if config.pagination == PaginationStyle.CURSOR:+ # Browse pages via an opaque cursor carried in the POST body; a missing cursor in the+ # response signals end of index.+ return JSONResponseCursorPaginator(cursor_path="cursor", cursor_param="cursor", param_location="json")+ # Search endpoints (synonyms/rules) page via a 0-based `page` in the POST body; the indices+ # listing pages via `page` in the query string.+ return AlgoliaPageNumberPaginator(+ page_size=config.page_size,+ base_page=0,+ page_param="page",+ param_location="json" if config.method == "POST" else "query",+ )+++def algolia_source(endpoint: str,application_id: str,api_key: str,index_name: str | None,- logger: FilteringBoundLogger,+ team_id: int,+ job_id: str,manager: ResumableSourceManager[AlgoliaResumeConfig],-) -> Iterator[Any]:+) -> SourceResponse:config = ALGOLIA_ENDPOINTS[endpoint]- headers = _get_headers(application_id, api_key)- url = _endpoint_url(application_id, config, index_name)- batcher = Batcher(logger=logger, chunk_size=5000, chunk_size_bytes=100 * 1024 * 1024)- session = make_tracked_session(redact_values=(api_key,))-- resume = manager.load_state() if manager.can_resume() else None+ is_cursor = config.pagination == PaginationStyle.CURSOR- if config.pagination == PaginationStyle.CURSOR:- yield from _iter_cursor(session, url, headers, config, logger, batcher, manager, resume)+ endpoint_config: Endpoint = {+ "path": _endpoint_path(config, index_name),+ "method": cast(HTTPMethodBasic, config.method),+ "data_selector": config.data_selector,+ "paginator": _build_paginator(config),+ }+ # Rows requested per page (`hitsPerPage`) travel where the page token does: in the POST body+ # for browse/search, in the query string for the GET indices listing.+ if config.method == "POST":+ endpoint_config["json"] = {"hitsPerPage": config.page_size}else:- yield from _iter_pages(session, url, headers, config, logger, batcher, manager, resume)+ endpoint_config["params"] = {"hitsPerPage": config.page_size}++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": _base_url(application_id),+ # The API key is supplied via the framework auth config so its value is redacted from+ # logs; only the non-secret application ID / content headers are set here.+ "headers": {+ "X-Algolia-Application-Id": application_id,+ "Accept": "application/json",+ "Content-Type": "application/json",+ },+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-Algolia-API-Key", "location": "header"},+ },+ "resource_defaults": {},+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],+ }- if batcher.should_yield(include_incomplete_chunk=True):- yield batcher.get_table()+ initial_paginator_state: Optional[dict[str, Any]] = None+ if manager.can_resume():+ resume = manager.load_state()+ if resume is not None:+ if is_cursor and resume.cursor is not None:+ initial_paginator_state = {"cursor": resume.cursor}+ elif not is_cursor and resume.page is not None:+ initial_paginator_state = {"page": resume.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; the hook fires AFTER a page is yielded so a crash+ # re-yields the last page (merge dedupes on the primary key) rather than skipping it.+ if not state:+ return+ if is_cursor:+ if state.get("cursor") is not None:+ manager.save_state(AlgoliaResumeConfig(cursor=state["cursor"]))+ elif state.get("page") is not None:+ manager.save_state(AlgoliaResumeConfig(page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ # Full-refresh endpoints with no stable datetime field to partition on.+ partition_count=1,+ partition_size=1,+ )def validate_credentials(@@ -284,30 +286,3 @@ def validate_credentials(f"Algolia returned an unexpected status ({response.status_code}). Check your Application ID ""and API key, then try again.",)---def algolia_source(- endpoint: str,- application_id: str,- api_key: str,- index_name: str | None,- logger: FilteringBoundLogger,- manager: ResumableSourceManager[AlgoliaResumeConfig],-) -> SourceResponse:- config = ALGOLIA_ENDPOINTS[endpoint]-- return SourceResponse(- name=endpoint,- items=lambda: get_rows(- endpoint=endpoint,- application_id=application_id,- api_key=api_key,- index_name=index_name,- logger=logger,- manager=manager,- ),- primary_keys=config.primary_keys,- # Full-refresh endpoints with no stable datetime field to partition on.- partition_count=1,- partition_size=1,- )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.pyindex 5f600c14e405..53ecd3ebf3f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.py@@ -21,7 +21,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.alfrom products.warehouse_sources.backend.temporal.data_imports.sources.algolia.settings import (ALGOLIA_ENDPOINTS,ENDPOINTS,- INCREMENTAL_FIELDS,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (@@ -29,7 +28,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom 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.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AlgoliaSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -120,23 +122,17 @@ The API key needs the ACLs for the data you want to sync:names: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- def _build_schema(endpoint: str) -> SourceSchema:- return SourceSchema(- name=endpoint,- # No Algolia endpoint exposes a server-side "updated since" filter, so every table- # is full refresh; the cursor/page tokens still make each one resumable.- supports_incremental=False,- supports_append=False,- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- should_sync_default=ALGOLIA_ENDPOINTS[endpoint].should_sync_default,- description=_ENDPOINT_DESCRIPTIONS.get(endpoint),- )-- schemas = [_build_schema(endpoint) 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+ # No Algolia endpoint exposes a server-side "updated since" filter, so every table is+ # full refresh (no incremental fields); the cursor/page tokens still make each one+ # resumable. An empty mapping keeps every endpoint full refresh, since+ # `build_endpoint_schemas` treats any present entry as incremental.+ return build_endpoint_schemas(+ ENDPOINTS,+ {},+ names,+ descriptions=_ENDPOINT_DESCRIPTIONS,+ should_sync_default={name: cfg.should_sync_default for name, cfg in ALGOLIA_ENDPOINTS.items()},+ )def validate_credentials(self, config: AlgoliaSourceConfig, team_id: int, schema_name: Optional[str] = None@@ -162,7 +158,8 @@ The API key needs the ACLs for the data you want to sync:application_id=config.application_id,api_key=config.api_key,index_name=config.index_name,- logger=inputs.logger,+ team_id=inputs.team_id,+ job_id=inputs.job_id,manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.pyindex 5230e5e12de5..b555ba39554c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py@@ -1,10 +1,11 @@+import jsonfrom typing import Anyimport pytest-from unittest.mock import MagicMock, patch+from unittest import mock-import pyarrow as paimport requests+from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia import (AlgoliaResumeConfig,@@ -12,28 +13,73 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.al_base_url,_endpoint_url,algolia_source,- get_rows,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.settings import ALGOLIA_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+# 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"+# validate_credentials builds its own tracked session in the algolia module.+ALGOLIA_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia.make_tracked_session"+)+-def _response(body: dict[str, Any], status_code: int = 200) -> MagicMock:- resp = MagicMock()+def _response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()resp.status_code = status_code- resp.ok = 200 <= status_code < 300- resp.json.return_value = body- resp.text = str(body)+ resp._content = json.dumps(body).encode()return resp-def _rows(tables: list[Any]) -> list[dict[str, Any]]:- out: list[dict[str, Any]] = []- for table in tables:- assert isinstance(table, pa.Table)- out.extend(table.to_pylist())- return out+def _make_manager(resume_state: AlgoliaResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request AT PREPARE TIME.++ ``request.params`` / ``request.json`` are single dicts mutated in place across pages, so+ inspecting them after the run shows only the final state — snapshot copies when each request+ is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append(+ {+ "method": request.method,+ "url": request.url,+ "params": dict(request.params or {}),+ "json": dict(request.json) if request.json is not None else None,+ }+ )+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _build(endpoint: str, manager: mock.MagicMock, index_name: str | None = "idx") -> Any:+ return algolia_source(+ endpoint=endpoint,+ application_id="APP",+ api_key="key",+ index_name=index_name,+ team_id=1,+ job_id="job",+ manager=manager,+ )+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]class TestBaseUrl:@@ -65,187 +111,169 @@ class TestEndpointUrl:assert _endpoint_url("APP", ALGOLIA_ENDPOINTS["indices"], None) == "https://APP.algolia.net/1/indexes"-class _Driver:- """Drives get_rows against a fake tracked session, capturing every request."""-- def __init__(self, responses: list[MagicMock]) -> None:- self.responses = iter(responses)- self.calls: list[dict[str, Any]] = []-- def _request(self, method: str, url: str, **kwargs: Any) -> MagicMock:- self.calls.append({"method": method, "url": url, "json": kwargs.get("json"), "params": kwargs.get("params")})- return next(self.responses)-- def run(self, endpoint: str, manager: MagicMock) -> list[dict[str, Any]]:- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia.make_tracked_session"- ) as mock_session_factory:- session = mock_session_factory.return_value- session.request.side_effect = self._request- tables = list(- get_rows(- endpoint=endpoint,- application_id="APP",- api_key="key",- index_name="idx",- logger=MagicMock(),- manager=manager,- )- )- return _rows(tables)---def _fresh_manager() -> MagicMock:- manager = MagicMock(spec=ResumableSourceManager)- manager.can_resume.return_value = False- return manager--class TestCursorPagination:- def test_pages_until_cursor_absent(self) -> None:- manager = _fresh_manager()- driver = _Driver(+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_pages_until_cursor_absent(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ calls = _wire(+ session,[_response({"hits": [{"objectID": "1"}], "cursor": "c1"}),_response({"hits": [{"objectID": "2"}]}),- ]+ ],)- rows = driver.run("records", manager)+ rows = _rows(_build("records", manager))assert [r["objectID"] for r in rows] == ["1", "2"]+ assert [c["method"] for c in calls] == ["POST", "POST"]+ assert calls[0]["url"] == "https://APP.algolia.net/1/indexes/idx/browse"# First browse request carries no cursor; the second carries the cursor returned first.- assert driver.calls[0]["json"] == {"hitsPerPage": 1000}- assert driver.calls[1]["json"] == {"hitsPerPage": 1000, "cursor": "c1"}-- def test_saves_cursor_after_non_terminal_page(self) -> None:- manager = _fresh_manager()- driver = _Driver(+ assert calls[0]["json"] == {"hitsPerPage": 1000}+ assert calls[1]["json"] == {"hitsPerPage": 1000, "cursor": "c1"}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_cursor_after_non_terminal_page(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ _wire(+ session,[_response({"hits": [{"objectID": "1"}], "cursor": "c1"}),_response({"hits": [{"objectID": "2"}]}),- ]+ ],)- driver.run("records", manager)+ _rows(_build("records", manager))saved = [call.args[0] for call in manager.save_state.call_args_list]assert saved == [AlgoliaResumeConfig(cursor="c1")]- def test_single_terminal_page_saves_nothing(self) -> None:- manager = _fresh_manager()- driver = _Driver([_response({"hits": [{"objectID": "only"}]})])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_single_terminal_page_saves_nothing(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ _wire(session, [_response({"hits": [{"objectID": "only"}]})])- rows = driver.run("records", manager)+ rows = _rows(_build("records", manager))assert [r["objectID"] for r in rows] == ["only"]+ assert session.send.call_count == 1manager.save_state.assert_not_called()- def test_resume_seeds_cursor(self) -> None:- manager = MagicMock(spec=ResumableSourceManager)- manager.can_resume.return_value = True- manager.load_state.return_value = AlgoliaResumeConfig(cursor="resumed")- driver = _Driver([_response({"hits": [{"objectID": "x"}]})])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_seeds_cursor(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager(AlgoliaResumeConfig(cursor="resumed"))+ calls = _wire(session, [_response({"hits": [{"objectID": "x"}]})])- driver.run("records", manager)+ _rows(_build("records", manager))- assert driver.calls[0]["json"] == {"hitsPerPage": 1000, "cursor": "resumed"}+ assert calls[0]["json"] == {"hitsPerPage": 1000, "cursor": "resumed"}class TestPagePagination:- def test_search_endpoint_stops_on_short_page(self) -> None:- manager = _fresh_manager()+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_search_endpoint_stops_on_short_page(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()# Fewer rows than the requested page size signals the last page for search endpoints.- driver = _Driver([_response({"hits": [{"objectID": "s1"}], "nbHits": 1})])+ calls = _wire(session, [_response({"hits": [{"objectID": "s1"}], "nbHits": 1})])- rows = driver.run("synonyms", manager)+ rows = _rows(_build("synonyms", manager))assert [r["objectID"] for r in rows] == ["s1"]- assert len(driver.calls) == 1+ assert len(calls) == 1manager.save_state.assert_not_called()- def test_search_endpoint_walks_multiple_pages(self, monkeypatch: pytest.MonkeyPatch) -> None:- manager = _fresh_manager()+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_search_endpoint_walks_multiple_pages(+ self, MockSession: mock.MagicMock, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ session = MockSession.return_value+ manager = _make_manager()monkeypatch.setattr(ALGOLIA_ENDPOINTS["synonyms"], "page_size", 2)- driver = _Driver(+ calls = _wire(+ session,[_response({"hits": [{"objectID": "a"}, {"objectID": "b"}], "nbHits": 3}),_response({"hits": [{"objectID": "c"}], "nbHits": 3}),- ]+ ],)- rows = driver.run("synonyms", manager)+ rows = _rows(_build("synonyms", manager))assert [r["objectID"] for r in rows] == ["a", "b", "c"]- assert [c["json"]["page"] for c in driver.calls] == [0, 1]+ # Search endpoints page via the POST body.+ assert [c["json"]["page"] for c in calls] == [0, 1]+ assert all(c["json"]["hitsPerPage"] == 2 for c in calls)saved = [call.args[0] for call in manager.save_state.call_args_list]assert saved == [AlgoliaResumeConfig(page=1)]- def test_indices_uses_nb_pages_to_terminate(self) -> None:- manager = _fresh_manager()- driver = _Driver(+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_indices_uses_nb_pages_to_terminate(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ calls = _wire(+ session,[_response({"items": [{"name": "i1"}], "nbPages": 2}),_response({"items": [{"name": "i2"}], "nbPages": 2}),- ]+ ],)- rows = driver.run("indices", manager)+ rows = _rows(_build("indices", manager, index_name=None))assert [r["name"] for r in rows] == ["i1", "i2"]+ assert len(calls) == 2# GET endpoints page via query params, and must request the configured page size so the# listing doesn't fall back to Algolia's small server-side default.- assert [c["params"]["page"] for c in driver.calls] == [0, 1]- assert all(c["params"]["hitsPerPage"] == ALGOLIA_ENDPOINTS["indices"].page_size for c in driver.calls)+ assert [c["method"] for c in calls] == ["GET", "GET"]+ assert [c["params"]["page"] for c in calls] == [0, 1]+ assert all(c["params"]["hitsPerPage"] == ALGOLIA_ENDPOINTS["indices"].page_size for c in calls)- def test_resume_seeds_page(self) -> None:- manager = MagicMock(spec=ResumableSourceManager)- manager.can_resume.return_value = True- manager.load_state.return_value = AlgoliaResumeConfig(page=3)- driver = _Driver([_response({"items": [{"name": "i"}], "nbPages": 4})])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_seeds_page(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager(AlgoliaResumeConfig(page=3))+ calls = _wire(session, [_response({"items": [{"name": "i"}], "nbPages": 4})])- driver.run("indices", manager)+ _rows(_build("indices", manager, index_name=None))- assert driver.calls[0]["params"]["page"] == 3+ assert calls[0]["params"]["page"] == 3class TestAlgoliaSourceResponse:@pytest.mark.parametrize("endpoint", list(ALGOLIA_ENDPOINTS.keys()))- def test_primary_keys_match_settings(self, endpoint: str) -> None:- manager = MagicMock(spec=ResumableSourceManager)- response = algolia_source(- endpoint=endpoint,- application_id="APP",- api_key="key",- index_name="idx",- logger=MagicMock(),- manager=manager,- )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_primary_keys_match_settings(self, MockSession: mock.MagicMock, endpoint: str) -> None:+ MockSession.return_value.headers = {}+ response = _build(endpoint, _make_manager())assert response.name == endpointassert response.primary_keys == ALGOLIA_ENDPOINTS[endpoint].primary_keys- def test_items_is_lazy(self) -> None:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_items_is_lazy(self, MockSession: mock.MagicMock) -> None:# Building the SourceResponse must not issue any request; only iterating items should.- manager = MagicMock(spec=ResumableSourceManager)- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia.make_tracked_session"- ) as factory:- algolia_source(- endpoint="records",- application_id="APP",- api_key="key",- index_name="idx",- logger=MagicMock(),- manager=manager,- )- factory.assert_not_called()+ session = MockSession.return_value+ session.headers = {}+ _build("records", _make_manager())+ session.send.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_application_id_header_is_set_on_session(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"hits": []})])++ _rows(_build("records", _make_manager()))++ assert session.headers.get("X-Algolia-Application-Id") == "APP"class TestValidateCredentials:- def _run(self, response: MagicMock, **kwargs: Any) -> tuple[bool, str | None]:- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia.make_tracked_session"- ) as factory:+ def _run(self, response: Any, **kwargs: Any) -> tuple[bool, str | None]:+ with mock.patch(ALGOLIA_SESSION_PATCH) as factory:session = factory.return_valuesession.get.return_value = responsesession.post.return_value = response@@ -277,9 +305,7 @@ class TestValidateCredentials:assert error is not Nonedef test_invalid_application_id_rejected_before_request(self) -> None:- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia.make_tracked_session"- ) as factory:+ with mock.patch(ALGOLIA_SESSION_PATCH) as factory:valid, error = validate_credentials(application_id="evil.com/", api_key="key", index_name="idx")assert valid is Falseassert error is not None@@ -287,9 +313,7 @@ class TestValidateCredentials:factory.return_value.post.assert_not_called()def test_network_error_returns_message(self) -> None:- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia.make_tracked_session"- ) as factory:+ with mock.patch(ALGOLIA_SESSION_PATCH) as factory:factory.return_value.get.side_effect = requests.ConnectionError("boom")valid, error = validate_credentials(application_id="APP", api_key="key")assert valid is False@@ -320,7 +344,9 @@ class TestValidateCredentials:def test_non_json_error_body_does_not_crash(self) -> None:# A non-JSON error body (e.g. an HTML 502 page) must not blow up validation; fall back to a# status-based message.- resp = _response({}, status_code=502)+ resp = mock.MagicMock()+ resp.status_code = 502+ resp.ok = Falseresp.json.side_effect = ValueError("no json")valid, error = self._run(resp, index_name="idx")assert valid is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia_source.pyindex 0d25382532f3..29b9e1cae125 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia_source.py@@ -153,7 +153,8 @@ class TestAlgoliaSource:application_id="APPID",api_key="test-key",index_name="my_index",- logger=inputs.logger,+ team_id=99,+ job_id="job-xyz",manager=manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/ashby.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/ashby.pyindex 79b0721ae327..0ae6a66a5d98 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/ashby.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/ashby.py@@ -1,29 +1,28 @@import dataclasses-from collections.abc import Iteratorfrom 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 requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.ashby.settings import ASHBY_ENDPOINTSfrom 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,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerASHBY_BASE_URL = "https://api.ashbyhq.com"PAGE_SIZE = 100 # Ashby's documented max (and default).-REQUEST_TIMEOUT_SECONDS = 60# Cheap endpoint to confirm a key is genuine when no specific schema is being validated.DEFAULT_PROBE_PATH = "department.list"AUTH_ERROR_HINT = "Ashby API authentication or permission error"-class AshbyRetryableError(Exception):- pass--class AshbyAPIError(Exception):pass@@ -33,11 +32,6 @@ class AshbyResumeConfig:cursor: str-def _auth(api_key: str) -> tuple[str, str]:- # Ashby uses HTTP Basic auth: API key as username, empty password.- return (api_key, "")--def _headers() -> dict[str, str]:return {"Content-Type": "application/json", "Accept": "application/json"}@@ -66,94 +60,88 @@ def _errors_from_payload(data: dict[str, Any]) -> list[Any]:return []-@retry(- retry=retry_if_exception_type((AshbyRetryableError, 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,- api_key: str,- path: str,- body: dict[str, Any],- logger: FilteringBoundLogger,-) -> dict[str, Any]:- response = session.post(- f"{ASHBY_BASE_URL}/{path}", json=body, auth=_auth(api_key), headers=_headers(), timeout=REQUEST_TIMEOUT_SECONDS- )-- if response.status_code == 429 or response.status_code >= 500:- raise AshbyRetryableError(f"Ashby API error (retryable): status={response.status_code}, path={path}")-- if response.status_code in (401, 403):- raise AshbyAPIError(f"{response.status_code} Client Error: {AUTH_ERROR_HINT} for path {path}")-- if not response.ok:- logger.error(f"Ashby API error: status={response.status_code}, body={response.text}, path={path}")- response.raise_for_status()-- data = response.json()- if not data.get("success", False):- is_auth, message = _classify_failure_message(_errors_from_payload(data))- if is_auth:- raise AshbyAPIError(f"{AUTH_ERROR_HINT} for path {path}: {message}")- raise AshbyAPIError(f"Ashby API error for path {path}: {message}")-- return data---def get_rows(- api_key: str,- endpoint: str,- logger: FilteringBoundLogger,- resumable_source_manager: ResumableSourceManager[AshbyResumeConfig],-) -> Iterator[list[dict[str, Any]]]:- config = ASHBY_ENDPOINTS[endpoint]- session = make_tracked_session()-- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- cursor: Optional[str] = resume.cursor if resume else None- if cursor:- logger.debug(f"Ashby: resuming {endpoint} from cursor")-- while True:- body: dict[str, Any] = {"limit": PAGE_SIZE}- if cursor:- body["cursor"] = cursor+class AshbyCursorPaginator(JSONResponseCursorPaginator):+ """Cursor-in-JSON-body pagination plus Ashby's HTTP-200 error envelope.- data = _fetch_page(session, api_key, config.path, body, logger)+ Ashby reports many failures as HTTP 200 with ``success: false`` and an ``errors``+ array — raise on those (auth-ish messages carry ``AUTH_ERROR_HINT`` so the job-level+ classifier treats them as non-retryable). Termination honors ``moreDataAvailable``,+ which can be false even when a ``nextCursor`` is present.+ """- results = data.get("results") or []- if results:- yield results+ def __init__(self, path: str) -> None:+ super().__init__(cursor_path="nextCursor", cursor_param="cursor", param_location="json")+ self._path = path- next_cursor = data.get("nextCursor")- if not data.get("moreDataAvailable", False) or not next_cursor:- break+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ payload = response.json()+ if not payload.get("success", False):+ is_auth, message = _classify_failure_message(_errors_from_payload(payload))+ if is_auth:+ raise AshbyAPIError(f"{AUTH_ERROR_HINT} for path {self._path}: {message}")+ raise AshbyAPIError(f"Ashby API error for path {self._path}: {message}")- cursor = next_cursor- # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages- # are persisted); merge/replace dedupes on the primary key.- resumable_source_manager.save_state(AshbyResumeConfig(cursor=cursor))+ super().update_state(response, data)+ if not payload.get("moreDataAvailable", False):+ self._has_next_page = Falsedef ashby_source(api_key: str,endpoint: str,- logger: FilteringBoundLogger,+ team_id: int,+ job_id: str,resumable_source_manager: ResumableSourceManager[AshbyResumeConfig],) -> SourceResponse:config = ASHBY_ENDPOINTS[endpoint]+ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": ASHBY_BASE_URL,+ "headers": _headers(),+ # Ashby uses HTTP Basic auth: API key as username, empty password.+ "auth": {"type": "http_basic", "username": api_key, "password": ""},+ "paginator": AshbyCursorPaginator(config.path),+ },+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "method": "post",+ "json": {"limit": PAGE_SIZE},+ "data_selector": "results",+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"cursor": resume.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; the checkpoint fires AFTER a page is yielded so a+ # crash re-fetches from the next page (already-yielded pages are persisted); merge/replace+ # dedupes on the primary key.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(AshbyResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None, # every Ashby endpoint is full refresh+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+return SourceResponse(name=endpoint,- items=lambda: get_rows(- api_key=api_key,- endpoint=endpoint,- logger=logger,- resumable_source_manager=resumable_source_manager,- ),+ items=lambda: resource,primary_keys=config.primary_key,partition_count=1,partition_size=1,@@ -166,14 +154,15 @@ def ashby_source(def check_access(api_key: str, path: str) -> tuple[int, Optional[str]]:"""Probe a single endpoint to validate credentials.- Returns a normalized ``(status, message)`` where status mimics HTTP semantics even when- Ashby reports the failure as HTTP 200 + ``success: false``:+ Ashby's RPC endpoints are POST-only and report many failures as HTTP 200 with+ ``success: false``, so the generic GET-based ``validate_via_probe`` can't express this+ check. Returns a normalized ``(status, message)`` where status mimics HTTP semantics:200 = reachable, 401 = bad key, 403 = valid key without scope, other = unexpected."""- session = make_tracked_session()+ session = make_tracked_session(redact_values=(api_key,))try:response = session.post(- f"{ASHBY_BASE_URL}/{path}", json={"limit": 1}, auth=_auth(api_key), headers=_headers(), timeout=15+ f"{ASHBY_BASE_URL}/{path}", json={"limit": 1}, auth=(api_key, ""), headers=_headers(), timeout=15)except Exception as e:return 0, f"Could not connect to Ashby: {e}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/source.pyindex cdffa3dac653..62973633b7ca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/source.py@@ -27,7 +27,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom 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.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AshbySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -89,19 +92,7 @@ You can create an API key under **Admin → API Keys** in Ashby. Grant read perm# Ashby exposes incremental sync only via an opaque syncToken and an unordered# `createdAfter` filter — neither maps safely onto PostHog's timestamp-watermark# model — so every endpoint is full refresh for now.- 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+ return build_endpoint_schemas(ENDPOINTS, {}, names)def validate_credentials(self, config: AshbySourceConfig, team_id: int, schema_name: Optional[str] = None@@ -144,6 +135,7 @@ You can create an API key under **Admin → API Keys** in Ashby. Grant read permreturn ashby_source(api_key=config.api_key,endpoint=inputs.schema_name,- logger=inputs.logger,+ team_id=inputs.team_id,+ job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.pyindex fa55c8ba90e5..580f9f062712 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py@@ -1,8 +1,12 @@+import jsonfrom typing import Any, Optionalimport pytestfrom unittest import mock+import requests+from requests import Response+from products.warehouse_sources.backend.temporal.data_imports.sources.ashby.ashby import (ASHBY_BASE_URL,AUTH_ERROR_HINT,@@ -12,51 +16,80 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ashby.ashb_errors_from_payload,ashby_source,check_access,- get_rows,)from products.warehouse_sources.backend.temporal.data_imports.sources.ashby.settings import ENDPOINTS-SESSION_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.ashby.ashby.make_tracked_session"+# 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"+# check_access builds its own tracked session in the ashby module.+ASHBY_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.ashby.ashby.make_tracked_session"+)-class FakeResponse:- def __init__(- self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, raise_json: bool = False- ) -> None:- self.status_code = status_code- self._json = json_data if json_data is not None else {}- self.text = str(self._json)- self._raise_json = raise_json+def _response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp- @property- def ok(self) -> bool:- return 200 <= self.status_code < 300- def json(self) -> dict[str, Any]:- if self._raise_json:- raise ValueError("no json")- return self._json+def _page(+ items: list[dict[str, Any]],+ *,+ more: bool = False,+ next_cursor: Optional[str] = None,+) -> Response:+ body: dict[str, Any] = {"success": True, "results": items, "moreDataAvailable": more}+ if next_cursor is not None:+ body["nextCursor"] = next_cursor+ return _response(body)+++def _make_manager(resume_state: AshbyResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager- def raise_for_status(self) -> None:- if not self.ok:- raise Exception(f"{self.status_code} Client Error")+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return snapshots of each request AT SEND TIME.-class FakeSession:- def __init__(self, responses: list[FakeResponse]) -> None:- self._responses = list(responses)- self.calls: list[dict[str, Any]] = []+ ``request.json`` is a single dict mutated in place across pages, so inspecting it after the+ run shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []- def post(self, url: str, json: Any = None, auth: Any = None, headers: Any = None, timeout: Any = None):- self.calls.append({"url": url, "json": json, "auth": auth, "headers": headers})- return self._responses[0] if len(self._responses) == 1 else self._responses.pop(0)+ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append(+ {+ "url": request.url,+ "method": request.method,+ "json": dict(request.json or {}),+ "auth": request.auth,+ }+ )+ return mock.MagicMock()+ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots-def _manager(can_resume: bool = False, state: Optional[AshbyResumeConfig] = None) -> mock.MagicMock:- manager = mock.MagicMock()- manager.can_resume.return_value = can_resume- manager.load_state.return_value = state- return manager++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _source(endpoint: str = "candidates", manager: Optional[mock.MagicMock] = None, api_key: str = "dummy-key"):+ return ashby_source(+ api_key=api_key,+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ )class TestClassifyFailureMessage:@@ -92,80 +125,126 @@ class TestErrorsFromPayload:assert _errors_from_payload(payload) == expected-class TestGetRows:- def test_paginates_until_no_more_data(self) -> None:- responses = [- FakeResponse(- json_data={"success": True, "results": [{"id": "1"}], "moreDataAvailable": True, "nextCursor": "c1"}- ),- FakeResponse(json_data={"success": True, "results": [{"id": "2"}], "moreDataAvailable": False}),- ]- session = FakeSession(responses)- manager = _manager()-- with mock.patch(SESSION_PATH, return_value=session):- batches = list(get_rows("dummy-key", "candidates", mock.MagicMock(), manager))-- assert batches == [[{"id": "1"}], [{"id": "2"}]]- # First call has no cursor, second forwards nextCursor.- assert "cursor" not in session.calls[0]["json"]- assert session.calls[1]["json"]["cursor"] == "c1"- assert session.calls[0]["json"]["limit"] == 100- assert session.calls[0]["auth"] == ("dummy-key", "")- assert session.calls[0]["url"] == f"{ASHBY_BASE_URL}/candidate.list"-- def test_saves_state_after_yielding_each_page(self) -> None:- responses = [- FakeResponse(- json_data={"success": True, "results": [{"id": "1"}], "moreDataAvailable": True, "nextCursor": "c1"}- ),- FakeResponse(json_data={"success": True, "results": [{"id": "2"}], "moreDataAvailable": False}),- ]- manager = _manager()-- with mock.patch(SESSION_PATH, return_value=FakeSession(responses)):- list(get_rows("k", "candidates", mock.MagicMock(), manager))+class TestPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_no_more_data(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _page([{"id": "1"}], more=True, next_cursor="c1"),+ _page([{"id": "2"}], more=False),+ ],+ )++ rows = _rows(_source("candidates"))++ assert rows == [{"id": "1"}, {"id": "2"}]+ # First call has no cursor, second forwards nextCursor; limit is sent in the JSON body.+ assert "cursor" not in snapshots[0]["json"]+ assert snapshots[1]["json"]["cursor"] == "c1"+ assert snapshots[0]["json"]["limit"] == 100+ assert snapshots[0]["url"] == f"{ASHBY_BASE_URL}/candidate.list"+ assert snapshots[0]["method"] == "POST"+ # Ashby authenticates via HTTP Basic: API key as username, empty password.+ assert snapshots[0]["auth"].username == "dummy-key"+ assert snapshots[0]["auth"].password == ""++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_state_after_yielding_each_page(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _page([{"id": "1"}], more=True, next_cursor="c1"),+ _page([{"id": "2"}], more=False),+ ],+ )+ manager = _make_manager()++ _rows(_source("candidates", manager))manager.save_state.assert_called_once_with(AshbyResumeConfig(cursor="c1"))- def test_resumes_from_saved_cursor(self) -> None:- responses = [FakeResponse(json_data={"success": True, "results": [{"id": "9"}], "moreDataAvailable": False})]- session = FakeSession(responses)- manager = _manager(can_resume=True, state=AshbyResumeConfig(cursor="resume-cursor"))+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_page([{"id": "9"}], more=False)])+ manager = _make_manager(AshbyResumeConfig(cursor="resume-cursor"))- with mock.patch(SESSION_PATH, return_value=session):- batches = list(get_rows("k", "candidates", mock.MagicMock(), manager))+ rows = _rows(_source("candidates", manager))- assert batches == [[{"id": "9"}]]- assert session.calls[0]["json"]["cursor"] == "resume-cursor"+ assert rows == [{"id": "9"}]+ assert snapshots[0]["json"]["cursor"] == "resume-cursor"- def test_empty_results_yield_nothing(self) -> None:- responses = [FakeResponse(json_data={"success": True, "results": [], "moreDataAvailable": False})]+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_results_yield_nothing(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_page([], more=False)])- with mock.patch(SESSION_PATH, return_value=FakeSession(responses)):- batches = list(get_rows("k", "users", mock.MagicMock(), _manager()))+ assert _rows(_source("users")) == []- assert batches == []+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_when_more_data_unavailable_even_with_cursor(self, MockSession) -> None:+ # Ashby can return a nextCursor alongside moreDataAvailable=false — that must terminate.+ session = MockSession.return_value+ _wire(session, [_page([{"id": "1"}], more=False, next_cursor="c9")])+ manager = _make_manager()- @pytest.mark.parametrize(- "response",- [- FakeResponse(status_code=401),- FakeResponse(status_code=403),- ],- )- def test_http_auth_errors_raise_matchable_api_error(self, response: FakeResponse) -> None:- with mock.patch(SESSION_PATH, return_value=FakeSession([response])):- with pytest.raises(AshbyAPIError) as exc:- list(get_rows("k", "candidates", mock.MagicMock(), _manager()))- assert f"{response.status_code} Client Error" in str(exc.value)-- def test_success_false_auth_error_raises_matchable_api_error(self) -> None:- response = FakeResponse(json_data={"success": False, "errors": ["Missing permission: candidatesRead"]})- with mock.patch(SESSION_PATH, return_value=FakeSession([response])):- with pytest.raises(AshbyAPIError) as exc:- list(get_rows("k", "candidates", mock.MagicMock(), _manager()))+ rows = _rows(_source("candidates", manager))++ assert rows == [{"id": "1"}]+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @pytest.mark.parametrize("status_code", [401, 403])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_http_auth_errors_raise_matchable_error(self, MockSession, status_code: int) -> None:+ session = MockSession.return_value+ _wire(session, [_response({}, status_code=status_code)])++ with pytest.raises(requests.HTTPError) as exc:+ _rows(_source("candidates"))+ assert f"{status_code} Client Error" in str(exc.value)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_success_false_auth_error_raises_matchable_api_error(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"success": False, "errors": ["Missing permission: candidatesRead"]})])++ with pytest.raises(AshbyAPIError) as exc:+ _rows(_source("candidates"))assert AUTH_ERROR_HINT in str(exc.value)+ assert "Missing permission: candidatesRead" in str(exc.value)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_success_false_non_auth_error_raises_without_auth_hint(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"success": False, "errors": ["validation failed"]})])++ with pytest.raises(AshbyAPIError) as exc:+ _rows(_source("candidates"))+ assert AUTH_ERROR_HINT not in str(exc.value)+ assert "validation failed" in str(exc.value)+++class FakeResponse:+ def __init__(+ self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, raise_json: bool = False+ ) -> None:+ self.status_code = status_code+ self._json = json_data if json_data is not None else {}+ self.text = str(self._json)+ self._raise_json = raise_json++ @property+ def ok(self) -> bool:+ return 200 <= self.status_code < 300++ def json(self) -> dict[str, Any]:+ if self._raise_json:+ raise ValueError("no json")+ return self._jsonclass TestCheckAccess:@@ -182,34 +261,51 @@ class TestCheckAccess:],)def test_status_mapping(self, response: FakeResponse, expected_status: int) -> None:- with mock.patch(SESSION_PATH, return_value=FakeSession([response])):+ session = mock.MagicMock()+ session.post.return_value = response+ with mock.patch(ASHBY_SESSION_PATCH, return_value=session):status, _message = check_access("k", "department.list")assert status == expected_status+ def test_probes_endpoint_with_basic_auth(self) -> None:+ session = mock.MagicMock()+ session.post.return_value = FakeResponse(json_data={"success": True, "results": []})+ with mock.patch(ASHBY_SESSION_PATCH, return_value=session):+ check_access("k", "department.list")+ call = session.post.call_args+ assert call.args[0] == f"{ASHBY_BASE_URL}/department.list"+ assert call.kwargs["auth"] == ("k", "")+ assert call.kwargs["json"] == {"limit": 1}+def test_connection_error_returns_zero(self) -> None:session = mock.MagicMock()session.post.side_effect = Exception("boom")- with mock.patch(SESSION_PATH, return_value=session):+ with mock.patch(ASHBY_SESSION_PATCH, return_value=session):status, message = check_access("k", "department.list")assert status == 0assert message is not None-class TestAshbySource:- def test_candidates_partitioned_by_created_at(self) -> None:- response = ashby_source("k", "candidates", mock.MagicMock(), _manager())+class TestAshbySourceResponse:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_candidates_partitioned_by_created_at(self, MockSession) -> None:+ response = _source("candidates")assert response.name == "candidates"assert response.primary_keys == ["id"]assert response.partition_mode == "datetime"+ assert response.partition_format == "month"assert response.partition_keys == ["createdAt"]- def test_reference_endpoint_is_unpartitioned(self) -> None:- response = ashby_source("k", "users", mock.MagicMock(), _manager())+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_reference_endpoint_is_unpartitioned(self, MockSession) -> None:+ response = _source("users")assert response.partition_mode is None+ assert response.partition_format is Noneassert response.partition_keys is Noneassert response.primary_keys == ["id"]- def test_all_endpoints_buildable(self) -> None:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_all_endpoints_buildable(self, MockSession) -> None:for endpoint in ENDPOINTS:- response = ashby_source("k", endpoint, mock.MagicMock(), _manager())+ response = _source(endpoint)assert response.primary_keys == ["id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.pyindex 71aebb142422..00bfca6112d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.py@@ -131,6 +131,8 @@ class TestAshbySource:def test_source_for_pipeline_plumbs_arguments(self, mock_ashby_source: mock.MagicMock) -> None:inputs = mock.MagicMock()inputs.schema_name = "candidates"+ inputs.team_id = 123+ inputs.job_id = "job-1"manager = mock.MagicMock()self.source.source_for_pipeline(self.config, manager, inputs)@@ -139,4 +141,6 @@ class TestAshbySource:kwargs = mock_ashby_source.call_args.kwargsassert kwargs["api_key"] == "ashby-key"assert kwargs["endpoint"] == "candidates"+ assert kwargs["team_id"] == 123+ assert kwargs["job_id"] == "job-1"assert kwargs["resumable_source_manager"] is managerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/blogger.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/blogger.pyindex 9d0f56e75247..667524dc7bb8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/blogger.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/blogger.py@@ -1,29 +1,29 @@import dataclasses-from collections.abc import Iteratorfrom datetime import UTC, date, datetime-from typing import Any-from urllib.parse import urlencode, urlsplit+from typing import Any, Optional+from urllib.parse import urlsplitimport requests-from structlog.types import FilteringBoundLogger-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.settings import (- BLOGGER_ENDPOINTS,- BloggerEndpointConfig,-)+from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.settings import BLOGGER_ENDPOINTSfrom 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,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpointfrom 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_probeBLOGGER_BASE_URL = "https://www.googleapis.com/blogger/v3"# Blogger caps `maxResults` per resource; 100 is comfortably within the limits for posts/comments/pages.DEFAULT_PAGE_SIZE = 100-REQUEST_TIMEOUT_SECONDS = 60---class BloggerRetryableError(Exception):- """Raised for transient Blogger API failures (429 / 5xx) that tenacity should retry."""@dataclasses.dataclass@@ -43,161 +43,141 @@ def _format_rfc3339(value: Any) -> str:return str(value)-def _headers() -> dict[str, str]:- return {"Accept": "application/json"}+class BloggerPageTokenPaginator(JSONResponseCursorPaginator):+ """Blogger's opaque `pageToken` cursor, with one twist: never checkpoint an empty page. An empty+ page yields no rows, so persisting its continuation token would let a crash skip past pages we+ never surfaced — re-walking the (cheap) empty pages on resume is the safe choice."""+ def __init__(self) -> None:+ super().__init__(cursor_path="nextPageToken", cursor_param="pageToken")+ self._last_page_had_items = True-def _raise_sanitized_for_status(response: requests.Response) -> None:- """Mirror `requests.Response.raise_for_status()` but strip the URL's query string before it lands- in an exception message. Blogger carries the API key in `?key=...`, and these import errors are- logged and captured by the shared non-retryable error handler — so the raw `raise_for_status()`- message would leak the key. The sanitized URL keeps the stable `.../blogger/v3` prefix that- `BloggerSource.get_non_retryable_errors()` matches on, so error classification is unaffected."""- if response.ok:- return- kind = "Client Error" if response.status_code < 500 else "Server Error"- safe_url = urlsplit(response.url)._replace(query="").geturl()- raise requests.HTTPError(f"{response.status_code} {kind}: {response.reason} for url: {safe_url}", response=response)+ def update_state(self, response: requests.Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ self._last_page_had_items = bool(data)+ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if not self._last_page_had_items:+ return None+ return super().get_resume_state()-def _build_url(path: str, params: dict[str, Any]) -> str:- return f"{BLOGGER_BASE_URL}{path}?{urlencode(params)}"---def _build_params(- config: BloggerEndpointConfig,- api_key: str,- page_token: str | None,- start_date: str | None,-) -> dict[str, Any]:- # The Google API key always rides as the `key` query param (Blogger has no header form for it).- params: dict[str, Any] = {"key": api_key}- if config.is_single_object:- return params-- params["maxResults"] = DEFAULT_PAGE_SIZE- if config.order_by:- params["orderBy"] = config.order_by- if start_date:- params["startDate"] = start_date- if page_token:- params["pageToken"] = page_token- return params---@retry(- retry=retry_if_exception_type((BloggerRetryableError, 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, url: str, headers: dict[str, str], logger: FilteringBoundLogger-) -> dict[str, Any]:- response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)- if response.status_code == 429 or response.status_code >= 500:- raise BloggerRetryableError(f"Blogger API error (retryable): status={response.status_code}")+def _make_sanitized_session(api_key: str) -> requests.Session:+ """Tracked session that strips the query string from the final response URL. Blogger carries the+ API key in `?key=...`, and both `raise_for_status()` and the client's retryable-error messages+ embed `response.url` — which the shared non-retryable error handler logs and surfaces. Stripping+ the query keeps the stable `.../blogger/v3` prefix that `BloggerSource.get_non_retryable_errors()`+ matches on, so error classification is unaffected while the key never leaks."""+ session = make_tracked_session(redact_values=(api_key,))+ original_send = session.send- if not response.ok:- logger.error(f"Blogger API error: status={response.status_code}, body={response.text}")- _raise_sanitized_for_status(response)+ def send_with_sanitized_url(request: Any, **kwargs: Any) -> requests.Response:+ response = original_send(request, **kwargs)+ if response.url:+ response.url = urlsplit(response.url)._replace(query="").geturl()+ return response- return response.json()+ session.send = send_with_sanitized_url # type: ignore[method-assign] # ty: ignore[invalid-assignment]+ return sessiondef validate_credentials(api_key: str, blog_id: str) -> tuple[bool, str | None]:"""Probe `blogs.get` for the configured blog. This confirms both the API key and that the key canread the target blog in a single cheap request."""- url = _build_url(f"/blogs/{blog_id}", {"key": api_key})- try:- response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_headers(), timeout=10)- except Exception:- return False, "Could not reach the Blogger API. Please try again."-- if response.status_code == 200:+ ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{BLOGGER_BASE_URL}/blogs/{blog_id}",+ headers={"Accept": "application/json"},+ auth=APIKeyAuth(api_key=api_key, name="key", location="query"),+ )+ if ok:return True, None- if response.status_code in (400, 401, 403):+ if status is None:+ return False, "Could not reach the Blogger API. Please try again."+ if status in (400, 401, 403):return False, "Your Blogger API key is invalid or does not have access to this blog."- if response.status_code == 404:+ if status == 404:return False, "No Blogger blog was found for that blog ID."- return False, f"The Blogger API returned an unexpected error (status {response.status_code})."---def get_rows(- api_key: str,- blog_id: str,- endpoint: str,- logger: FilteringBoundLogger,- resumable_source_manager: ResumableSourceManager[BloggerResumeConfig],- should_use_incremental_field: bool = False,- db_incremental_field_last_value: Any = None,- incremental_field: str | None = None,-) -> Iterator[Any]:- config = BLOGGER_ENDPOINTS[endpoint]- # One session reused across every page so urllib3 keeps the connection alive. The API key is in the- # query string, so register it for redaction in logged URLs and captured samples.- session = make_tracked_session(redact_values=(api_key,))- headers = _headers()-- if config.is_single_object:- data = _fetch_page(session, _build_url(config.path.format(blog_id=blog_id), {"key": api_key}), headers, logger)- yield [data]- return-- # `startDate` is the only server-side filter Blogger offers; map the user's incremental cursor- # (always `published`) onto it. On first sync there's no last value, so we pull full history.- start_date: str | None = None- if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:- start_date = _format_rfc3339(db_incremental_field_last_value)-- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- page_token = resume.page_token if resume is not None else None-- base_path = config.path.format(blog_id=blog_id)- while True:- url = _build_url(base_path, _build_params(config, api_key, page_token, start_date))- data = _fetch_page(session, url, headers, logger)-- items = data.get("items", [])- next_token = data.get("nextPageToken")-- if items:- yield items- # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last page- # rather than skipping it — merge dedupes on the primary key.- if next_token:- resumable_source_manager.save_state(BloggerResumeConfig(page_token=next_token))-- if not next_token:- break- page_token = next_token+ return False, f"The Blogger API returned an unexpected error (status {status})."def blogger_source(api_key: str,blog_id: str,endpoint: str,- logger: FilteringBoundLogger,+ team_id: int,+ job_id: str,resumable_source_manager: ResumableSourceManager[BloggerResumeConfig],should_use_incremental_field: bool = False,- db_incremental_field_last_value: Any = None,- incremental_field: str | None = None,+ db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = BLOGGER_ENDPOINTS[endpoint]+ endpoint_def: Endpoint+ if config.is_single_object:+ # `blogs.get` returns a single blog object rather than a paginated `items` list.+ endpoint_def = {+ "path": config.path.format(blog_id=blog_id),+ "data_selector": "$",+ "paginator": SinglePagePaginator(),+ }+ else:+ params: dict[str, Any] = {"maxResults": DEFAULT_PAGE_SIZE}+ if config.order_by:+ params["orderBy"] = config.order_by+ # A body without `items` is a legit zero-row page (Blogger omits the key when empty), so the+ # selector is deliberately not required.+ endpoint_def = {+ "path": config.path.format(blog_id=blog_id),+ "params": params,+ "data_selector": "items",+ "paginator": BloggerPageTokenPaginator(),+ }+ # `startDate` is the only server-side filter Blogger offers; map the user's incremental cursor+ # (always `published`) onto it. On first sync there's no last value, so we pull full history.+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:+ endpoint_def["incremental"] = {+ "start_param": "startDate",+ "cursor_path": "published",+ "convert": _format_rfc3339,+ }++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BLOGGER_BASE_URL,+ "headers": {"Accept": "application/json"},+ # The Google API key always rides as the `key` query param (Blogger has no header form).+ "auth": {"type": "api_key", "name": "key", "api_key": api_key, "location": "query"},+ "session": _make_sanitized_session(api_key),+ },+ "resource_defaults": {},+ "resources": [{"name": endpoint, "endpoint": endpoint_def}],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.page_token:+ initial_paginator_state = {"cursor": resume.page_token}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; the checkpoint fires AFTER a page is yielded so a+ # crash re-yields the last page (merge dedupes on the primary key) rather than skipping it.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(BloggerResumeConfig(page_token=state["cursor"]))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if should_use_incremental_field else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+return SourceResponse(name=endpoint,- items=lambda: get_rows(- api_key=api_key,- blog_id=blog_id,- endpoint=endpoint,- logger=logger,- resumable_source_manager=resumable_source_manager,- should_use_incremental_field=should_use_incremental_field,- db_incremental_field_last_value=db_incremental_field_last_value,- incremental_field=incremental_field,- ),+ items=lambda: resource,primary_keys=config.primary_keys,# Blogger only returns list results newest-first (its sort-direction param is unavailable), so# incremental endpoints scroll descending. Full-refresh endpoints don't care about order.@@ -207,4 +187,5 @@ def blogger_source(partition_mode="datetime" if config.partition_key else None,partition_format="month" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=resource.column_hints,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.pyindex 64c13dd82280..81de18153407 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/source.py@@ -146,11 +146,11 @@ The API key reads publicly visible content (live posts, pages, and comments). Drapi_key=config.api_key,blog_id=config.blog_id,endpoint=inputs.schema_name,- logger=inputs.logger,+ team_id=inputs.team_id,+ job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,should_use_incremental_field=inputs.should_use_incremental_field,db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,- incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger.pyindex 99db8c976276..54574320beca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger.py@@ -1,109 +1,76 @@+import jsonfrom datetime import UTC, date, datetime, timedelta, timezone-from typing import Any, cast+from typing import Anyimport pytest-from unittest.mock import MagicMock, patch+from unittest import mockimport requestsfrom parameterized import parameterized-from products.warehouse_sources.backend.temporal.data_imports.sources.blogger import bloggerfrom products.warehouse_sources.backend.temporal.data_imports.sources.blogger.blogger import (BloggerResumeConfig,- _build_params,_format_rfc3339,blogger_source,- get_rows,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.blogger.settings import BLOGGER_ENDPOINTS---class _FakeResponse:- def __init__(- self,- status_code: int,- json_data: dict | None = None,- *,- url: str = "https://www.googleapis.com/blogger/v3",- reason: str = "OK",- text: str = "",- ) -> None:- self.status_code = status_code- self._json = json_data or {}- self.text = text- self.url = url- self.reason = reason- self.ok = 200 <= status_code < 300-- def json(self) -> dict:- return self._json-- def raise_for_status(self) -> None:- if not self.ok:- raise requests.HTTPError(- f"{self.status_code} error for url: {self.url}", response=cast(requests.Response, self)- )+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+# blogger builds its (sanitized) tracked session itself, so both the pipeline transport and+# validate_credentials patch the blogger module's make_tracked_session.+BLOGGER_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.blogger.blogger.make_tracked_session"+)-class _FakeSession:- def __init__(self, response: _FakeResponse) -> None:- self._response = response- self.requested_urls: list[str] = []- def get(self, url: str, headers: dict | None = None, timeout: int | None = None) -> _FakeResponse:- self.requested_urls.append(url)- return self._response+def _response(body: dict[str, Any], *, status_code: int = 200, url: str = "", reason: str = "OK") -> requests.Response:+ resp = requests.Response()+ resp.status_code = status_code+ resp.reason = reason+ resp.url = url or "https://www.googleapis.com/blogger/v3/x"+ resp._content = json.dumps(body).encode()+ return resp-class _FakeResumableManager:- def __init__(self, state: BloggerResumeConfig | None = None) -> None:- self._state = state- self.saved: list[BloggerResumeConfig] = []+def _make_manager(resume_state: BloggerResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager- def can_resume(self) -> bool:- return self._state is not None- def load_state(self) -> BloggerResumeConfig | None:- return self._state+def _wire(session: mock.MagicMock, responses: list[requests.Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return snapshots of each request AT PREPARE TIME.- def save_state(self, data: BloggerResumeConfig) -> None:- self.saved.append(data)+ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the run+ shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []+ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"params": dict(request.params or {}), "url": request.url, "auth": request.auth})+ return mock.MagicMock()-class _SequentialFetch:- """Stand-in for `_fetch_page` that returns canned responses in order and records request URLs."""+ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots- def __init__(self, responses: list[dict]) -> None:- self._responses = list(responses)- self.urls: list[str] = []- def __call__(self, session: Any, url: str, headers: dict, logger: Any) -> dict:- self.urls.append(url)- return self._responses.pop(0)+def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]-def _collect(- endpoint: str,- manager: _FakeResumableManager,- fetch: _SequentialFetch,- **kwargs: Any,-) -> list[dict]:- rows: list[dict] = []- with (- patch.object(blogger, "_fetch_page", fetch),- patch.object(blogger, "make_tracked_session", lambda **_: MagicMock()),- ):- for batch in get_rows(- api_key="K",- blog_id="BID",- endpoint=endpoint,- logger=MagicMock(),- resumable_source_manager=manager, # type: ignore[arg-type]- **kwargs,- ):- rows.extend(batch)- return rows+def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> Any:+ return blogger_source(+ api_key="K",+ blog_id="BID",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )class TestFormatRfc3339:@@ -127,30 +94,6 @@ class TestFormatRfc3339:assert "+00:00" not in _format_rfc3339(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))-class TestBuildParams:- def test_single_object_sends_only_key(self) -> None:- params = _build_params(BLOGGER_ENDPOINTS["blogs"], "K", page_token=None, start_date=None)- assert params == {"key": "K"}-- def test_posts_sends_max_results_and_order_by(self) -> None:- params = _build_params(BLOGGER_ENDPOINTS["posts"], "K", page_token=None, start_date=None)- assert params["key"] == "K"- assert params["maxResults"] == 100- assert params["orderBy"] == "published"- assert "startDate" not in params- assert "pageToken" not in params-- def test_comments_has_no_order_by(self) -> None:- # comments.listByBlog rejects ordering params, so we never send orderBy for it.- params = _build_params(BLOGGER_ENDPOINTS["comments"], "K", page_token=None, start_date=None)- assert "orderBy" not in params-- def test_start_date_and_page_token_included(self) -> None:- params = _build_params(BLOGGER_ENDPOINTS["posts"], "K", page_token="TOK", start_date="2026-03-04T00:00:00Z")- assert params["startDate"] == "2026-03-04T00:00:00Z"- assert params["pageToken"] == "TOK"--class TestValidateCredentials:@parameterized.expand([@@ -162,84 +105,144 @@ class TestValidateCredentials:("server_error", 500, False),])- def test_status_mapping(self, _name: str, status: int, expected_ok: bool) -> None:- session = _FakeSession(_FakeResponse(status))- with patch.object(blogger, "make_tracked_session", lambda **_: session):- ok, error = validate_credentials("K", "BID")+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_status_mapping(self, _name: str, status: int, expected_ok: bool, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.return_value = mock.MagicMock(status_code=status)+ ok, error = validate_credentials("K", "BID")assert ok is expected_okif not expected_ok:assert error- def test_network_error_returns_false(self) -> None:- class _Boom:- def get(self, *args: Any, **kwargs: Any) -> Any:- raise requests.ConnectionError("boom")-- with patch.object(blogger, "make_tracked_session", lambda **_: _Boom()):- ok, error = validate_credentials("K", "BID")+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_probe_sends_key_as_query_auth(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("K", "BID")+ call = MockSession.return_value.get.call_args+ assert call.args[0].endswith("/blogs/BID")+ auth = call.kwargs["auth"]+ assert isinstance(auth, APIKeyAuth)+ assert (auth.api_key, auth.name, auth.location) == ("K", "key", "query")++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_network_error_returns_false(self, MockSession: mock.MagicMock) -> None:+ MockSession.return_value.get.side_effect = requests.ConnectionError("boom")+ ok, error = validate_credentials("K", "BID")assert ok is Falseassert errorclass TestGetRows:- def test_single_object_yields_one_row(self) -> None:- fetch = _SequentialFetch([{"id": "B1", "name": "My blog"}])- manager = _FakeResumableManager()- rows = _collect("blogs", manager, fetch)- assert rows == [{"id": "B1", "name": "My blog"}]- assert manager.saved == []- assert "/blogs/BID?key=K" in fetch.urls[0]+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_single_object_yields_one_row(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"id": "B1", "name": "My blog"})])- def test_list_paginates_and_saves_state_only_when_more_pages(self) -> None:- fetch = _SequentialFetch(+ manager = _make_manager()+ rows = _rows(_source("blogs", manager))++ assert rows == [{"id": "B1", "name": "My blog"}]+ manager.save_state.assert_not_called()+ assert snapshots[0]["url"].endswith("/blogs/BID")+ # `blogs.get` sends no list params; the key rides via the framework's query-param auth.+ assert snapshots[0]["params"] == {}++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_api_key_rides_as_query_param_auth(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"items": [{"id": "p1"}]})])++ _rows(_source("posts", _make_manager()))++ auth = snapshots[0]["auth"]+ assert isinstance(auth, APIKeyAuth)+ assert (auth.api_key, auth.name, auth.location) == ("K", "key", "query")++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_list_paginates_and_saves_state_only_when_more_pages(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,[- {"items": [{"id": "p1"}, {"id": "p2"}], "nextPageToken": "T2"},- {"items": [{"id": "p3"}], "nextPageToken": None},- ]+ _response({"items": [{"id": "p1"}, {"id": "p2"}], "nextPageToken": "T2"}),+ _response({"items": [{"id": "p3"}], "nextPageToken": None}),+ ],)- manager = _FakeResumableManager()- rows = _collect("posts", manager, fetch)++ manager = _make_manager()+ rows = _rows(_source("posts", manager))+assert [r["id"] for r in rows] == ["p1", "p2", "p3"]# State is saved once — after the first page (which had a next token), not after the last.- assert manager.saved == [BloggerResumeConfig(page_token="T2")]+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == BloggerResumeConfig(page_token="T2")# The second request carries the page token from the first response.- assert "pageToken=T2" in fetch.urls[1]+ assert snapshots[0]["params"].get("pageToken") is None+ assert snapshots[1]["params"]["pageToken"] == "T2"# Full refresh sends no startDate.- assert all("startDate" not in url for url in fetch.urls)-- def test_incremental_maps_last_value_to_start_date(self) -> None:- fetch = _SequentialFetch([{"items": [{"id": "p1"}], "nextPageToken": None}])- manager = _FakeResumableManager()- _collect(- "posts",- manager,- fetch,- should_use_incremental_field=True,- db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),- incremental_field="published",+ assert all("startDate" not in s["params"] for s in snapshots)++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_posts_sends_max_results_and_order_by(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"items": [{"id": "p1"}]})])++ _rows(_source("posts", _make_manager()))++ assert snapshots[0]["params"]["maxResults"] == 100+ assert snapshots[0]["params"]["orderBy"] == "published"++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_comments_has_no_order_by(self, MockSession: mock.MagicMock) -> None:+ # comments.listByBlog rejects ordering params, so we never send orderBy for it.+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"items": [{"id": "c1"}]})])++ _rows(_source("comments", _make_manager()))++ assert "orderBy" not in snapshots[0]["params"]++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_incremental_maps_last_value_to_start_date(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"items": [{"id": "p1"}], "nextPageToken": None})])++ _rows(+ _source(+ "posts",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ ))- # Colons are percent-encoded by urlencode.- assert "startDate=2026-03-04T02%3A58%3A14Z" in fetch.urls[0]-- def test_first_sync_without_last_value_sends_no_start_date(self) -> None:- fetch = _SequentialFetch([{"items": [{"id": "p1"}], "nextPageToken": None}])- manager = _FakeResumableManager()- _collect(- "posts",- manager,- fetch,- should_use_incremental_field=True,- db_incremental_field_last_value=None,- incremental_field="published",++ assert snapshots[0]["params"]["startDate"] == "2026-03-04T02:58:14Z"++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_first_sync_without_last_value_sends_no_start_date(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"items": [{"id": "p1"}], "nextPageToken": None})])++ _rows(+ _source(+ "posts",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ ))- assert "startDate" not in fetch.urls[0]- def test_resume_starts_from_saved_page_token(self) -> None:- fetch = _SequentialFetch([{"items": [{"id": "p9"}], "nextPageToken": None}])- manager = _FakeResumableManager(BloggerResumeConfig(page_token="RESUME"))- rows = _collect("posts", manager, fetch)+ assert "startDate" not in snapshots[0]["params"]++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_resume_starts_from_saved_page_token(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"items": [{"id": "p9"}], "nextPageToken": None})])++ manager = _make_manager(BloggerResumeConfig(page_token="RESUME"))+ rows = _rows(_source("posts", manager))+assert [r["id"] for r in rows] == ["p9"]- assert "pageToken=RESUME" in fetch.urls[0]+ assert snapshots[0]["params"]["pageToken"] == "RESUME"@parameterized.expand([@@ -254,27 +257,48 @@ class TestGetRows:),])- def test_empty_items_never_save_state(self, _name: str, responses: list[dict], expected_requests: int) -> None:- fetch = _SequentialFetch(responses)- manager = _FakeResumableManager()- rows = _collect("posts", manager, fetch)+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_empty_items_never_save_state(+ self, _name: str, responses: list[dict], expected_requests: int, MockSession: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response(body) for body in responses])++ manager = _make_manager()+ rows = _rows(_source("posts", manager))+assert rows == []# Empty pages never persist a resume token: a crash mid-sequence re-walks the empty pages# rather than skipping past them, so no unseen data is missed on resume.- assert manager.saved == []- assert len(fetch.urls) == expected_requests+ manager.save_state.assert_not_called()+ assert len(snapshots) == expected_requestsif expected_requests > 1:# The continuation token from the empty page still drives the follow-up request.- assert "pageToken=T2" in fetch.urls[1]+ assert snapshots[1]["params"]["pageToken"] == "T2"++ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_missing_items_key_is_a_zero_row_page(self, MockSession: mock.MagicMock) -> None:+ # Blogger omits `items` entirely when there is nothing to return — that's a legit empty+ # page, not a changed response shape, so it must not raise.+ session = MockSession.return_value+ _wire(session, [_response({"kind": "blogger#postList"})])++ rows = _rows(_source("posts", _make_manager()))++ assert rows == []-class TestFetchPageErrorSanitization:- def test_client_error_strips_api_key_but_keeps_matchable_prefix(self) -> None:+class TestErrorSanitization:+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_client_error_strips_api_key_but_keeps_matchable_prefix(self, MockSession: mock.MagicMock) -> None:# The real URL carries the key in the query string; the raised error must not leak it.leaky_url = "https://www.googleapis.com/blogger/v3/blogs/BID/posts?key=SECRETKEY&maxResults=100"- session = _FakeSession(_FakeResponse(400, url=leaky_url, reason="Bad Request"))+ session = MockSession.return_value+ _wire(session, [_response({}, status_code=400, url=leaky_url, reason="Bad Request")])+with pytest.raises(requests.HTTPError) as exc_info:- blogger._fetch_page(session, leaky_url, {}, MagicMock()) # type: ignore[arg-type]+ _rows(_source("posts", _make_manager()))+message = str(exc_info.value)assert "SECRETKEY" not in message# The non-retryable matcher keys are prefixes of this message, so error classification still works.@@ -283,39 +307,24 @@ class TestFetchPageErrorSanitization:class TestBloggerSourceResponse:@parameterized.expand([("posts", "desc"), ("comments", "desc"), ("blogs", "asc"), ("pages", "asc")])- def test_sort_mode_matches_incremental(self, endpoint: str, expected: str) -> None:- response = blogger_source(- api_key="K",- blog_id="BID",- endpoint=endpoint,- logger=MagicMock(),- resumable_source_manager=MagicMock(),- )+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_sort_mode_matches_incremental(self, endpoint: str, expected: str, MockSession: mock.MagicMock) -> None:+ response = _source(endpoint, _make_manager())assert response.name == endpointassert response.primary_keys == ["id"]assert response.sort_mode == expected@parameterized.expand([("posts",), ("comments",)])- def test_incremental_endpoints_partition_by_published(self, endpoint: str) -> None:- response = blogger_source(- api_key="K",- blog_id="BID",- endpoint=endpoint,- logger=MagicMock(),- resumable_source_manager=MagicMock(),- )+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_incremental_endpoints_partition_by_published(self, endpoint: str, MockSession: mock.MagicMock) -> None:+ response = _source(endpoint, _make_manager())assert response.partition_mode == "datetime"assert response.partition_keys == ["published"]assert response.partition_format == "month"@parameterized.expand([("blogs",), ("pages",)])- def test_full_refresh_endpoints_have_no_partition(self, endpoint: str) -> None:- response = blogger_source(- api_key="K",- blog_id="BID",- endpoint=endpoint,- logger=MagicMock(),- resumable_source_manager=MagicMock(),- )+ @mock.patch(BLOGGER_SESSION_PATCH)+ def test_full_refresh_endpoints_have_no_partition(self, endpoint: str, MockSession: mock.MagicMock) -> None:+ response = _source(endpoint, _make_manager())assert response.partition_mode is Noneassert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger_source.pyindex f6347d159b3b..8f99b2139d9d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/blogger/tests/test_blogger_source.py@@ -172,9 +172,10 @@ class TestBloggerPipelinePlumbing:assert captured["api_key"] == "K"assert captured["blog_id"] == "BID"assert captured["endpoint"] == "comments"+ assert captured["team_id"] == 1+ assert captured["job_id"] == "job-id"assert captured["should_use_incremental_field"] is Trueassert captured["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"- assert captured["incremental_field"] == "published"def test_source_for_pipeline_clears_last_value_when_not_incremental(self) -> None:captured: dict[str, Any] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.pyindex 479269d3c270..519098c4dc0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py@@ -1,11 +1,26 @@import refrom abc import ABC, abstractmethod-from typing import Any, Optional+from typing import Any, Literal, Optionalfrom requests import Request, Responsefrom .jsonpath_utils import TJsonPath, find_values+# Where a paginator writes its pagination fields. "query" (default) mutates request.params;+# "json" mutates the POST body — for APIs that carry page/cursor/limit inside the JSON payload.+ParamLocation = Literal["query", "json"]+++def _inject_param(request: Request, location: ParamLocation, name: str, value: Any) -> None:+ if location == "json":+ if request.json is None:+ request.json = {}+ request.json[name] = value+ else:+ if request.params is None:+ request.params = {}+ request.params[name] = value+class BasePaginator(ABC):def __init__(self) -> None:@@ -126,18 +141,18 @@ class JSONResponseCursorPaginator(BasePaginator):self,cursor_path: TJsonPath = "cursors.next",cursor_param: str = "cursor",+ param_location: ParamLocation = "query",) -> None:super().__init__()self.cursor_path = cursor_pathself.cursor_param = cursor_param+ self.param_location = param_locationself._cursor_value: Optional[str] = Nonedef init_request(self, request: Request) -> None:# Apply a seeded resume cursor to the first request.if self._cursor_value is not None:- if request.params is None:- request.params = {}- request.params[self.cursor_param] = self._cursor_value+ _inject_param(request, self.param_location, self.cursor_param, self._cursor_value)def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:try:@@ -152,9 +167,7 @@ class JSONResponseCursorPaginator(BasePaginator):def update_request(self, request: Request) -> None:if self._cursor_value is not None:- if request.params is None:- request.params = {}- request.params[self.cursor_param] = self._cursor_value+ _inject_param(request, self.param_location, self.cursor_param, self._cursor_value)def get_resume_state(self) -> Optional[dict[str, Any]]:return {"cursor": self._cursor_value} if self._has_next_page and self._cursor_value is not None else None@@ -180,6 +193,7 @@ class OffsetPaginator(BasePaginator):total_header: Optional[str] = None,maximum_offset: Optional[int] = None,stop_after_empty_page: bool = True,+ param_location: ParamLocation = "query",) -> None:super().__init__()self.limit = limit@@ -192,12 +206,11 @@ class OffsetPaginator(BasePaginator):self.total_header = total_headerself.maximum_offset = maximum_offsetself.stop_after_empty_page = stop_after_empty_page+ self.param_location = param_locationdef init_request(self, request: Request) -> None:- if request.params is None:- request.params = {}- request.params[self.offset_param] = self.offset- request.params[self.limit_param] = self.limit+ _inject_param(request, self.param_location, self.offset_param, self.offset)+ _inject_param(request, self.param_location, self.limit_param, self.limit)def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:if self.stop_after_empty_page and (data is None or len(data) == 0):@@ -238,9 +251,7 @@ class OffsetPaginator(BasePaginator):self._has_next_page = Truedef update_request(self, request: Request) -> None:- if request.params is None:- request.params = {}- request.params[self.offset_param] = self.offset+ _inject_param(request, self.param_location, self.offset_param, self.offset)def get_resume_state(self) -> Optional[dict[str, Any]]:# self.offset already points at the next page to fetch (update_state incremented it).@@ -262,22 +273,24 @@ class PageNumberPaginator(BasePaginator):base_page: int = 0,page: Optional[int] = None,page_param: str = "page",- total_path: Optional[TJsonPath] = "total",+ total_path: Optional[TJsonPath] = None,maximum_page: Optional[int] = None,stop_after_empty_page: bool = True,+ param_location: ParamLocation = "query",) -> None:super().__init__()self.base_page = base_pageself.page = page if page is not None else base_pageself.page_param = page_param+ # jsonpath to the TOTAL NUMBER OF PAGES in the response body (e.g. "pagination.total_pages").+ # When set, pagination stops after the last page instead of paying one extra empty-page request.self.total_path = total_pathself.maximum_page = maximum_pageself.stop_after_empty_page = stop_after_empty_page+ self.param_location = param_locationdef init_request(self, request: Request) -> None:- if request.params is None:- request.params = {}- request.params[self.page_param] = self.page+ _inject_param(request, self.param_location, self.page_param, self.page)def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:if self.stop_after_empty_page and (data is None or len(data) == 0):@@ -290,12 +303,23 @@ class PageNumberPaginator(BasePaginator):self._has_next_page = Falsereturn+ if self.total_path:+ try:+ values = find_values(self.total_path, response.json())+ if values:+ total_pages = values[0]+ # self.page now points at the NEXT page; the last valid page is+ # base_page + total_pages - 1.+ if isinstance(total_pages, int) and self.page > self.base_page + total_pages - 1:+ self._has_next_page = False+ return+ except Exception:+ pass+self._has_next_page = Truedef update_request(self, request: Request) -> None:- if request.params is None:- request.params = {}- request.params[self.page_param] = self.page+ _inject_param(request, self.param_location, self.page_param, self.page)def get_resume_state(self) -> Optional[dict[str, Any]]:# self.page already points at the next page to fetch (update_state incremented it).diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.pyindex a37b82c29ad9..d2f16dc35372 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py@@ -260,3 +260,52 @@ class TestOffsetPaginatorTotalHeader:resp = _make_response({}, headers={"X-Total": "5"})p.update_state(resp, data=[{}, {}]) # offset -> 2, below 5 -> continueassert p.has_next_page is True+++class TestJsonBodyPagination:+ def test_offset_paginator_injects_into_json_body(self) -> None:+ p = OffsetPaginator(limit=50, total_path=None, param_location="json")+ req = Request(method="POST", url="https://api.example.com/search", json=None)+ p.init_request(req)+ assert req.json == {"offset": 0, "limit": 50}+ assert not req.params++ p.update_state(_make_response(), data=[{} for _ in range(50)])+ p.update_request(req)+ assert req.json["offset"] == 50++ def test_page_number_paginator_injects_into_json_body(self) -> None:+ p = PageNumberPaginator(base_page=0, page_param="page", param_location="json")+ req = Request(method="POST", url="https://api.example.com/search", json={"query": ""})+ p.init_request(req)+ assert req.json == {"query": "", "page": 0}++ def test_cursor_paginator_injects_into_json_body(self) -> None:+ p = JSONResponseCursorPaginator(cursor_path="cursor", cursor_param="cursor", param_location="json")+ p.update_state(_make_response({"cursor": "abc"}))+ req = Request(method="POST", url="https://api.example.com/browse", json={"hitsPerPage": 1000})+ p.update_request(req)+ assert req.json == {"hitsPerPage": 1000, "cursor": "abc"}+++class TestPageNumberTotalPages:+ def test_stops_after_last_page_per_total_pages(self) -> None:+ p = PageNumberPaginator(base_page=1, total_path="pagination.total_pages")+ resp = _make_response({"pagination": {"total_pages": 2}})+ p.update_state(resp, data=[{}]) # fetched page 1 of 2 -> continue+ assert p.has_next_page is True+ p.update_state(resp, data=[{}]) # fetched page 2 of 2 -> stop, no extra request+ assert p.has_next_page is False++ def test_zero_based_pages_respect_total(self) -> None:+ p = PageNumberPaginator(base_page=0, total_path="pages")+ resp = _make_response({"pages": 1})+ p.update_state(resp, data=[{}]) # fetched page 0, total 1 page -> stop+ assert p.has_next_page is False++ def test_missing_total_falls_back_to_empty_page_stop(self) -> None:+ p = PageNumberPaginator(base_page=1, total_path="pagination.total_pages")+ p.update_state(_make_response({}), data=[{}])+ assert p.has_next_page is True+ p.update_state(_make_response({}), data=[])+ assert p.has_next_page is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.pyindex 22a7feaf26b6..7b7ba956ea9c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py@@ -55,6 +55,7 @@ class PageNumberPaginatorConfig(PaginatorTypeConfig, total=False):page_param: Optional[str]total_path: Optional[TJsonPath]maximum_page: Optional[int]+ param_location: Optional[str] # "query" (default) or "json" (POST-body pagination)class OffsetPaginatorConfig(PaginatorTypeConfig, total=False):@@ -63,7 +64,9 @@ class OffsetPaginatorConfig(PaginatorTypeConfig, total=False):offset_param: Optional[str]limit_param: Optional[str]total_path: Optional[TJsonPath]+ total_header: Optional[str]maximum_offset: Optional[int]+ param_location: Optional[str] # "query" (default) or "json" (POST-body pagination)class HeaderLinkPaginatorConfig(PaginatorTypeConfig, total=False):@@ -77,6 +80,7 @@ class JSONResponsePaginatorConfig(PaginatorTypeConfig, total=False):class JSONResponseCursorPaginatorConfig(PaginatorTypeConfig, total=False):cursor_path: Optional[TJsonPath]cursor_param: Optional[str]+ param_location: Optional[str] # "query" (default) or "json" (POST-body pagination)PaginatorConfig = (