: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 apify_dataset to rest_source (batch 1) (#71524)
Tom Owers458d50e72be1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/apify_dataset.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/apify_dataset.pyindex 73419cd2f5e7..0cd02b11a6e2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/apify_dataset.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/apify_dataset.py@@ -1,28 +1,28 @@import dataclasses-from collections.abc import Iterator-from typing import Any-from urllib.parse import quote, urlencode+from typing import Any, Optional+from urllib.parse import quote-import requests-from structlog.types import FilteringBoundLogger-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter--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.apify_dataset.settings import (APIFY_BASE_URL,PRIMARY_KEYS,)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 (+ OffsetPaginator,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe# One request to /datasets/{id}/items returns this many rows. The dataset endpoints carry a high# rate limit (~400 req/s), so a large page keeps the round-trip count down on big datasets.PAGE_SIZE = 1000---class ApifyRetryableError(Exception):- pass+# Apify reports the dataset's total item count in this response header (the body is a bare JSON array).+APIFY_TOTAL_HEADER = "X-Apify-Pagination-Total"@dataclasses.dataclass@@ -32,135 +32,83 @@ class ApifyResumeConfig:offset: int = 0-def _get_headers(api_token: str) -> dict[str, str]:- return {- "Authorization": f"Bearer {api_token}",- "Accept": "application/json",- }---def _items_url(dataset_id: str, offset: int, limit: int) -> str:- # `format=json` returns a JSON array of the raw rows; offset/limit drive the pagination.- params = {"offset": offset, "limit": limit, "format": "json"}+def _items_path(dataset_id: str) -> str:# Encode the dataset_id as a single path segment so a crafted value can't inject extra path- # segments or query params (e.g. dropping the enforced offset/limit).- return f"{APIFY_BASE_URL}/datasets/{quote(dataset_id, safe='')}/items?{urlencode(params)}"---def validate_credentials(api_token: str, dataset_id: str) -> tuple[bool, str | None]:- """Probe the dataset itself so a bad token (401) and a wrong/inaccessible dataset (404) are both caught."""- # Encode the dataset_id as a single path segment so a crafted value can't escape the path.- url = f"{APIFY_BASE_URL}/datasets/{quote(dataset_id, safe='')}"- try:- response = make_tracked_session().get(url, headers=_get_headers(api_token), timeout=10)- except Exception:- return False, "Could not reach the Apify API. Please try again."-- if response.status_code == 200:- return True, None- if response.status_code in (401, 403):- return False, "Invalid Apify API token, or the token cannot access this dataset."- if response.status_code == 404:- return False, "Dataset not found. Check the dataset ID and that the token can access it."- return False, f"Unexpected response from Apify (status {response.status_code})."---@retry(- retry=retry_if_exception_type((ApifyRetryableError, 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-) -> tuple[list[dict[str, Any]], int]:- """Fetch one page of dataset items. Returns the rows plus the dataset's total item count.-- Apify reports the total via the ``X-Apify-Pagination-Total`` response header rather than in the body- (the body is a bare JSON array), so we read it from there to know when to stop paging.- """- response = session.get(url, headers=headers, timeout=60)-- if response.status_code == 429 or response.status_code >= 500:- raise ApifyRetryableError(f"Apify API error (retryable): status={response.status_code}, url={url}")-- if not response.ok:- logger.error(f"Apify API error: status={response.status_code}, body={response.text}, url={url}")- response.raise_for_status()-- items = response.json()- if not isinstance(items, list):- # The items endpoint always returns a JSON array for format=json; anything else means the- # request was misrouted (e.g. an error object). That's a permanent contract violation, so raise- # a non-retryable error to fail loudly rather than waiting through every retry attempt.- raise ValueError(f"Unexpected Apify response shape (not a list), url={url}")-- total_header = response.headers.get("X-Apify-Pagination-Total")- try:- total = int(total_header) if total_header is not None else len(items)- except (TypeError, ValueError):- total = len(items)- return items, total---def get_rows(- api_token: str,- dataset_id: str,- logger: FilteringBoundLogger,- resumable_source_manager: ResumableSourceManager[ApifyResumeConfig],-) -> Iterator[Any]:- headers = _get_headers(api_token)- batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)- # One session reused across every page so urllib3 keeps the connection alive between requests.- session = make_tracked_session()-- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- offset = resume.offset if resume else 0- if resume:- logger.debug(f"Apify: resuming dataset {dataset_id} from offset {offset}")-- while True:- url = _items_url(dataset_id, offset, PAGE_SIZE)- items, total = _fetch_page(session, url, headers, logger)-- if not items:- break-- offset += len(items)- more_pages = offset < total-- for item in items:- batcher.batch(item)-- if batcher.should_yield():- yield batcher.get_table()- # Save AFTER yielding (and only when more rows remain) so a crash re-yields the last- # page rather than skipping it. The dataset is append-only, so the re-pulled rows are- # identical; full refresh tolerates the rare resume-window overlap.- if more_pages:- resumable_source_manager.save_state(ApifyResumeConfig(offset=offset))-- if not more_pages:- break-- if batcher.should_yield(include_incomplete_chunk=True):- yield batcher.get_table()+ # segments or query params.+ return f"/datasets/{quote(dataset_id, safe='')}/items"def apify_dataset_source(api_token: str,dataset_id: str,endpoint: str,- logger: FilteringBoundLogger,+ team_id: int,+ job_id: str,resumable_source_manager: ResumableSourceManager[ApifyResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:+ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": APIFY_BASE_URL,+ "auth": {"type": "bearer", "token": api_token},+ # Total lives in a response header, not the body; the bare JSON array is the row list.+ "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None, total_header=APIFY_TOTAL_HEADER),+ },+ "resource_defaults": {},+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": _items_path(dataset_id),+ "params": {"format": "json"},+ # The body is a bare JSON array; require it to be a list so a misrouted request+ # returning an error object fails loud instead of syncing the object as a row.+ "data_selector_required": True,+ },+ }+ ],+ }++ 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 = {"offset": resume.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("offset") is not None:+ resumable_source_manager.save_state(ApifyResumeConfig(offset=int(state["offset"])))++ 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(- api_token=api_token,- dataset_id=dataset_id,- logger=logger,- resumable_source_manager=resumable_source_manager,- ),+ items=lambda: resource,primary_keys=PRIMARY_KEYS.get(endpoint),+ column_hints=resource.column_hints,+ )+++def validate_credentials(api_token: str, dataset_id: str) -> tuple[bool, str | None]:+ """Probe the dataset itself so a bad token (401/403) and a wrong/inaccessible dataset (404) are both caught."""+ ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_token,)),+ f"{APIFY_BASE_URL}/datasets/{quote(dataset_id, safe='')}",+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},)+ if ok:+ return True, None+ if status in (401, 403):+ return False, "Invalid Apify API token, or the token cannot access this dataset."+ if status == 404:+ return False, "Dataset not found. Check the dataset ID and that the token can access it."+ if status is None:+ return False, "Could not reach the Apify API. Please try again."+ return False, f"Unexpected response from Apify (status {status})."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/settings.pyindex 25eeb42fab46..c79c865cdf3b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/settings.py@@ -18,7 +18,6 @@ PRIMARY_KEYS: dict[str, list[str] | None] = {}# No advertised incremental fields: dataset items are append-only with no server-side `updated_after`-# style filter, so an "incremental" sync would still page through every row. Ship full refresh only.-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {- DATASET_ITEMS_ENDPOINT: [],-}+# style filter, so an "incremental" sync would still page through every row. Ship full refresh only —+# leaving the endpoint out of the map keeps `build_endpoint_schemas` from advertising incremental sync.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/source.pyindex 4034c915baef..cbc173bb8a56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/source.py@@ -19,14 +19,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.apify_datavalidate_credentials as validate_apify_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.settings import (+ DATASET_ITEMS_ENDPOINT,ENDPOINTS,INCREMENTAL_FIELDS,- PRIMARY_KEYS,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom 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 ApifyDatasetSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -106,21 +109,14 @@ The token needs read access to the dataset's storage.""",names: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- schemas = [- SourceSchema(- name=endpoint,- supports_incremental=False,- supports_append=False,- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- detected_primary_keys=PRIMARY_KEYS.get(endpoint),- description="The rows produced by the Apify dataset. Columns are defined by the Actor that produced them. Full refresh only — the whole dataset is re-imported on every sync.",- )- 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,+ INCREMENTAL_FIELDS,+ names,+ descriptions={+ DATASET_ITEMS_ENDPOINT: "The rows produced by the Apify dataset. Columns are defined by the Actor that produced them. Full refresh only — the whole dataset is re-imported on every sync."+ },+ )def validate_credentials(self, config: ApifyDatasetSourceConfig, team_id: int, schema_name: Optional[str] = None@@ -140,6 +136,8 @@ The token needs read access to the dataset's storage.""",api_token=config.api_token,dataset_id=config.dataset_id,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, # full refresh only)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.pyindex 48d0ec11155e..12a8dfacf922 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py@@ -1,252 +1,145 @@+import jsonfrom typing import Anyimport pytestfrom unittest import mock-import pyarrow as pa-import requests-from parameterized import parameterized+from requests import Response-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset import apify_datasetfrom products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.apify_dataset import (ApifyResumeConfig,- ApifyRetryableError,- _fetch_page,- _items_url,apify_dataset_source,- get_rows,validate_credentials,)+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+APIFY_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.apify_dataset.make_tracked_session"+)-def _response(status_code: int, *, json_body: Any = None, headers: dict[str, str] | None = None) -> mock.Mock:- response = mock.Mock(spec=requests.Response)- response.status_code = status_code- response.ok = 200 <= status_code < 300- response.text = ""- response.headers = headers or {}- response.json.return_value = json_body- response.raise_for_status.side_effect = (- None if response.ok else requests.HTTPError(f"{status_code} Client Error", response=response)- )- return response+def _response(body: Any, *, total: int | None = None) -> Response:+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ if total is not None:+ resp.headers["X-Apify-Pagination-Total"] = str(total)+ return resp-def _small_batcher(**kwargs: Any) -> Batcher:- # Force a tiny chunk so a yield fires after a couple of rows without building thousands of dicts.- return Batcher(logger=kwargs["logger"], chunk_size=2, chunk_size_bytes=kwargs["chunk_size_bytes"])+def _make_manager(resume_state: ApifyResumeConfig | 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[email protected](autouse=True)-def _no_sleep():- # The tenacity retry decorator sleeps between attempts; zero it so retry tests stay instant.- with mock.patch("time.sleep", return_value=None):- yield+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ session.headers = {}+ params: list[dict[str, Any]] = []-class TestItemsUrl:- @parameterized.expand(- [- ("first_page", "ds1", 0, 1000),- ("offset_page", "ds1", 2000, 500),- ]- )- def test_items_url_contains_pagination_params(self, _name: str, dataset_id: str, offset: int, limit: int) -> None:- url = _items_url(dataset_id, offset, limit)- assert url.startswith(f"https://api.apify.com/v2/datasets/{dataset_id}/items?")- assert f"offset={offset}" in url- assert f"limit={limit}" in url- assert "format=json" in url-- def test_items_url_encodes_dataset_id_as_path_segment(self) -> None:- # A crafted dataset_id must not be able to inject extra path segments or query params- # (e.g. dropping the enforced offset/limit); it has to stay a single encoded path segment.- url = _items_url("evil/items?format=json#", 0, 1000)- assert url.startswith("https://api.apify.com/v2/datasets/evil%2Fitems%3Fformat%3Djson%23/items?")- assert "offset=0" in url- assert "limit=1000" in url+ def _prepare(request: Any) -> mock.MagicMock:+ params.append(dict(request.params or {}))+ return mock.MagicMock()+ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return params+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]-class TestValidateCredentials:- @parameterized.expand(- [- ("ok", 200, True),- ("unauthorized", 401, False),- ("forbidden", 403, False),- ("not_found", 404, False),- ("unexpected", 500, False),- ]- )- def test_status_code_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:- session = mock.Mock()- session.get.return_value = _response(status_code)- with mock.patch.object(apify_dataset, "make_tracked_session", return_value=session):- ok, error = validate_credentials("token", "ds1")- assert ok is expected_ok- assert (error is None) is expected_ok-- def test_network_error_is_not_valid(self) -> None:- session = mock.Mock()- session.get.side_effect = requests.ConnectionError("boom")- with mock.patch.object(apify_dataset, "make_tracked_session", return_value=session):- ok, error = validate_credentials("token", "ds1")- assert ok is False- assert error is not None---class TestFetchPage:- def test_reads_total_from_pagination_header(self) -> None:- session = mock.Mock()- session.get.return_value = _response(200, json_body=[{"a": 1}], headers={"X-Apify-Pagination-Total": "42"})- items, total = _fetch_page(session, "https://api.apify.com/v2/datasets/ds1/items", {}, mock.Mock())- assert items == [{"a": 1}]- assert total == 42-- def test_total_falls_back_to_item_count_without_header(self) -> None:- session = mock.Mock()- session.get.return_value = _response(200, json_body=[{"a": 1}, {"a": 2}], headers={})- items, total = _fetch_page(session, "https://api.apify.com/v2/datasets/ds1/items", {}, mock.Mock())- assert total == 2-- @parameterized.expand([("empty", ""), ("non_numeric", "abc")])- def test_total_falls_back_to_item_count_for_malformed_header(self, _name: str, header_value: str) -> None:- session = mock.Mock()- session.get.return_value = _response(- 200, json_body=[{"a": 1}, {"a": 2}], headers={"X-Apify-Pagination-Total": header_value}- )- items, total = _fetch_page(session, "https://api.apify.com/v2/datasets/ds1/items", {}, mock.Mock())- assert total == 2-- @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])- def test_retryable_statuses_eventually_reraise(self, _name: str, status_code: int) -> None:- session = mock.Mock()- session.get.return_value = _response(status_code)- with pytest.raises(ApifyRetryableError):- _fetch_page(session, "https://api.apify.com/v2/datasets/ds1/items", {}, mock.Mock())- assert session.get.call_count == 5-- def test_retries_then_succeeds(self) -> None:- session = mock.Mock()- session.get.side_effect = [- _response(503),- _response(200, json_body=[{"a": 1}], headers={"X-Apify-Pagination-Total": "1"}),- ]- items, total = _fetch_page(session, "https://api.apify.com/v2/datasets/ds1/items", {}, mock.Mock())- assert items == [{"a": 1}]- assert session.get.call_count == 2-- @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])- def test_client_errors_raise_immediately(self, _name: str, status_code: int) -> None:- session = mock.Mock()- session.get.return_value = _response(status_code)- with pytest.raises(requests.HTTPError):- _fetch_page(session, "https://api.apify.com/v2/datasets/ds1/items", {}, mock.Mock())- assert session.get.call_count == 1-- def test_non_list_body_raises_without_retrying(self) -> None:- session = mock.Mock()- session.get.return_value = _response(200, json_body={"error": "nope"})- # A non-list 200 body is a permanent contract violation, so it raises ValueError (not a- # retryable error) and exits immediately rather than waiting through all retry attempts.- with pytest.raises(ValueError):- _fetch_page(session, "https://api.apify.com/v2/datasets/ds1/items", {}, mock.Mock())- assert session.get.call_count == 1---def _resume_manager(saved: ApifyResumeConfig | None = None) -> mock.Mock:- manager = mock.Mock()- manager.can_resume.return_value = saved is not None- manager.load_state.return_value = saved- return manager+def _run(manager, responses):+ return apify_dataset_source(+ api_token="tok",+ dataset_id="ds1",+ endpoint="dataset_items",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )-def _collect_rows(tables: list[pa.Table]) -> list[dict[str, Any]]:- rows: list[dict[str, Any]] = []- for table in tables:- rows.extend(table.to_pylist())- return rows---class TestGetRows:- def test_paginates_until_offset_reaches_total(self) -> None:- manager = _resume_manager()- pages = [- ([{"i": 0}, {"i": 1}], 5),- ([{"i": 2}, {"i": 3}], 5),- ([{"i": 4}], 5),- ]- with (- mock.patch.object(apify_dataset, "make_tracked_session", return_value=mock.Mock()),- mock.patch.object(apify_dataset, "PAGE_SIZE", 2),- mock.patch.object(apify_dataset, "_fetch_page", side_effect=pages) as fetch,- ):- rows = _collect_rows(list(get_rows("token", "ds1", mock.Mock(), manager)))-- assert fetch.call_count == 3- assert [r["i"] for r in rows] == [0, 1, 2, 3, 4]- # The offset advances on each request: 0 -> 2 -> 4.- offsets = [call.args[1] for call in fetch.call_args_list]- assert "offset=0" in offsets[0]- assert "offset=2" in offsets[1]- assert "offset=4" in offsets[2]-- def test_resumes_from_saved_offset(self) -> None:- manager = _resume_manager(ApifyResumeConfig(offset=2))- with (- mock.patch.object(apify_dataset, "make_tracked_session", return_value=mock.Mock()),- mock.patch.object(apify_dataset, "PAGE_SIZE", 2),- mock.patch.object(apify_dataset, "_fetch_page", side_effect=[([{"i": 2}], 3)]) as fetch,- ):- list(get_rows("token", "ds1", mock.Mock(), manager))-- assert "offset=2" in fetch.call_args_list[0].args[1]-- def test_saves_state_after_yield_with_next_offset(self) -> None:- manager = _resume_manager()- pages = [- ([{"i": 0}, {"i": 1}], 4),- ([{"i": 2}, {"i": 3}], 4),- ]- with (- mock.patch.object(apify_dataset, "make_tracked_session", return_value=mock.Mock()),- mock.patch.object(apify_dataset, "PAGE_SIZE", 2),- mock.patch.object(apify_dataset, "Batcher", _small_batcher),- mock.patch.object(apify_dataset, "_fetch_page", side_effect=pages),- ):- list(get_rows("token", "ds1", mock.Mock(), manager))-- # After the first page (offset advanced to 2) more rows remain, so state is saved at offset 2.- saved_offsets = [call.args[0].offset for call in manager.save_state.call_args_list]- assert 2 in saved_offsets-- def test_does_not_save_state_on_final_page(self) -> None:- manager = _resume_manager()- with (- mock.patch.object(apify_dataset, "make_tracked_session", return_value=mock.Mock()),- mock.patch.object(apify_dataset, "PAGE_SIZE", 2),- mock.patch.object(apify_dataset, "Batcher", _small_batcher),- mock.patch.object(apify_dataset, "_fetch_page", side_effect=[([{"i": 0}, {"i": 1}], 2)]),- ):- list(get_rows("token", "ds1", mock.Mock(), manager))+class TestPagination:+ @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_progresses_offset_and_terminates_on_header_total(self, MockSession) -> None:+ session = MockSession.return_value+ # total=3: page 1 (2 rows, full) -> continue; page 2 (offset 2, 1 row) -> offset 4 >= 3 -> stop.+ params = _wire(session, [_response([{"i": 0}, {"i": 1}], total=3), _response([{"i": 2}], total=3)])++ manager = _make_manager()+ rows = _rows(_run(manager, None))++ assert [r["i"] for r in rows] == [0, 1, 2]+ assert params[0]["offset"] == 0+ assert params[0]["limit"] == 2+ assert params[0]["format"] == "json"+ assert params[1]["offset"] == 2+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == ApifyResumeConfig(offset=2)++ @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_short_page_terminates(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"i": 0}], total=1)])++ manager = _make_manager()+ rows = _rows(_run(manager, None))++ assert [r["i"] for r in rows] == [0]+ assert session.send.call_count == 1manager.save_state.assert_not_called()- def test_empty_dataset_yields_nothing(self) -> None:- manager = _resume_manager()- with (- mock.patch.object(apify_dataset, "make_tracked_session", return_value=mock.Mock()),- mock.patch.object(apify_dataset, "_fetch_page", side_effect=[([], 0)]),- ):- tables = list(get_rows("token", "ds1", mock.Mock(), manager))+ @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_offset(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"i": 200}], total=201)])++ manager = _make_manager(ApifyResumeConfig(offset=200))+ _rows(_run(manager, None))++ assert params[0]["offset"] == 200++ @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_non_list_body_raises_loudly(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"error": "wrong shape"}, total=0)])++ # A misrouted request returning an error object (not a list) must fail loud, not sync it as a row.+ with pytest.raises(ValueError, match="list response body"):+ _rows(_run(_make_manager(), None))- assert tables == []+class TestValidateCredentials:+ @mock.patch(APIFY_SESSION_PATCH)+ def test_ok(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert validate_credentials("tok", "ds1") == (True, None)++ @mock.patch(APIFY_SESSION_PATCH)+ def test_unauthorized_message(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)+ ok, msg = validate_credentials("tok", "ds1")+ assert ok is False+ assert "token" in (msg or "")-class TestApifyDatasetSource:- def test_source_response_shape(self) -> None:- response = apify_dataset_source("token", "ds1", "dataset_items", mock.Mock(), _resume_manager())- assert response.name == "dataset_items"- # Arbitrary dataset rows have no unique key, so the table is full-refresh only.- assert response.primary_keys is None- assert response.sort_mode == "asc"+ @mock.patch(APIFY_SESSION_PATCH)+ def test_not_found_message(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=404)+ ok, msg = validate_credentials("tok", "ds1")+ assert ok is False+ assert "Dataset not found" in (msg or "")++ @mock.patch(APIFY_SESSION_PATCH)+ def test_network_error_message(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ ok, msg = validate_credentials("tok", "ds1")+ assert ok is False+ assert "reach the Apify API" in (msg or "")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset_source.pyindex 85fd640ff7d0..45ef47669c9e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset_source.py@@ -92,7 +92,8 @@ class TestApifyDatasetSource:def test_source_for_pipeline_plumbs_arguments(self) -> None:inputs = mock.Mock()inputs.schema_name = "dataset_items"- inputs.logger = mock.Mock()+ inputs.team_id = 7+ inputs.job_id = "job-1"manager = mock.Mock()with mock.patch.object(source_module, "apify_dataset_source", return_value="sentinel") as build:result = self.source.source_for_pipeline(_config(), manager, inputs)@@ -101,6 +102,8 @@ class TestApifyDatasetSource:api_token="apify_api_token",dataset_id="ds1",endpoint="dataset_items",- logger=inputs.logger,+ team_id=7,+ job_id="job-1",resumable_source_manager=manager,+ db_incremental_field_last_value=None,)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 4b2d39b43d63..479269d3c270 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@@ -177,6 +177,7 @@ class OffsetPaginator(BasePaginator):offset_param: str = "offset",limit_param: str = "limit",total_path: Optional[TJsonPath] = "total",+ total_header: Optional[str] = None,maximum_offset: Optional[int] = None,stop_after_empty_page: bool = True,) -> None:@@ -186,6 +187,9 @@ class OffsetPaginator(BasePaginator):self.offset_param = offset_paramself.limit_param = limit_paramself.total_path = total_path+ # Some APIs report the grand total in a response header (e.g. X-*-Total) rather than the body;+ # when set, this takes precedence over total_path for the stop check.+ self.total_header = total_headerself.maximum_offset = maximum_offsetself.stop_after_empty_page = stop_after_empty_page@@ -206,6 +210,16 @@ class OffsetPaginator(BasePaginator):self._has_next_page = Falsereturn+ if self.total_header:+ raw_total = response.headers.get(self.total_header)+ if raw_total is not None:+ try:+ if self.offset >= int(raw_total):+ self._has_next_page = False+ return+ except (TypeError, ValueError):+ pass+if self.total_path:try:values = find_values(self.total_path, response.json())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 804c2cbcde39..c0eb9e7bf5f4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -241,6 +241,14 @@ class RESTClient:if isinstance(data, list) and len(data) == 1:data = data[0]else:+ # No selector: the whole body is the row list. With ``required``, a non-list body means+ # the response shape changed (e.g. an error object on a 200) — fail loud rather than+ # wrapping the stray object as a single row.+ if required and not isinstance(body, list):+ raise ValueError(+ f"Required a list response body, got {type(body).__name__}. "+ "The API response shape may have changed."+ )data = bodyif data is None: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 4f93b51231fb..a37b82c29ad9 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@@ -246,3 +246,17 @@ class TestPaginatorResume:req = Request(method="GET", url="https://api.example.com/page1")resumed.init_request(req)assert req.url == "https://api.example.com/page2"+++class TestOffsetPaginatorTotalHeader:+ def test_stops_when_offset_reaches_header_total(self) -> None:+ p = OffsetPaginator(limit=2, total_path=None, total_header="X-Total")+ resp = _make_response({}, headers={"X-Total": "2"})+ p.update_state(resp, data=[{}, {}]) # full page, offset -> 2, total 2 -> stop+ assert p.has_next_page is False++ def test_continues_when_below_header_total(self) -> None:+ p = OffsetPaginator(limit=2, total_path=None, total_header="X-Total")+ resp = _make_response({}, headers={"X-Total": "5"})+ p.update_state(resp, data=[{}, {}]) # offset -> 2, below 5 -> continue+ assert p.has_next_page is Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_required_selector.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_required_selector.pyindex 02187534c817..4ab387a96c97 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_required_selector.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_required_selector.py@@ -24,3 +24,12 @@ class TestRequiredDataSelector:def test_absent_key_is_silent_when_not_required(self) -> None:# Backward compatible: without required, a missing key still silently yields nothing.assert _client()._extract_response({"unexpected": "envelope"}, "data", required=False) == []+++class TestRequiredListBody:+ def test_non_list_body_raises_when_required_and_no_selector(self) -> None:+ with pytest.raises(ValueError, match="list response body"):+ _client()._extract_response({"error": "x"}, None, required=True)++ def test_list_body_ok_when_required_and_no_selector(self) -> None:+ assert _client()._extract_response([{"id": 1}], None, required=True) == [{"id": 1}]