: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): implement apify_dataset import source (#66735)
Tom Owersb37f043f12d9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 921d8393662c..159a0bb11c23 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -50,6 +50,7 @@ the row lists both.| algolia | HTTP | requests | ✅ || amazon_ads | HTTP | requests | ✅ || amplitude | HTTP | requests | ✅ |+| apify_dataset | HTTP | requests | ✅ || apollo | HTTP | requests | ✅ || appsflyer | HTTP (CSV reports) | requests | ✅ || asana | HTTP | requests | ✅ |@@ -304,7 +305,6 @@ doesn't conflict with concurrent PRs.- amazon_selling_partner- amazon_sns- amazon_sqs-- apify_dataset- appcues- appfigures- appfollowdiff --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.pynew file mode 100644index 000000000000..73419cd2f5e7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/apify_dataset.py@@ -0,0 +1,166 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import quote, urlencode++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 Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from 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.resumable import ResumableSourceManager++# 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+++class ApifyResumeConfig:+ # Absolute offset of the next dataset row to fetch. Apify datasets are append-only and returned in+ # stable storage order, so an offset always points at the same row — making it a safe resume cursor.+ 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"}+ # 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()+++def apify_dataset_source(+ api_token: str,+ dataset_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ApifyResumeConfig],+) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ dataset_id=dataset_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=PRIMARY_KEYS.get(endpoint),+ )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.pynew file mode 100644index 000000000000..25eeb42fab46--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/settings.py@@ -0,0 +1,24 @@+from products.warehouse_sources.backend.types import IncrementalField++APIFY_BASE_URL = "https://api.apify.com/v2"++# Apify exposes the rows produced by an Actor run as a single dataset. The dataset is addressed by a+# datasetId (or the `username~dataset-name` shorthand) and queried via GET /datasets/{id}/items. The+# rows are arbitrary Actor output, so this source ships exactly one table whose columns are whatever+# the Actor stored.+DATASET_ITEMS_ENDPOINT = "dataset_items"++ENDPOINTS = (DATASET_ITEMS_ENDPOINT,)++# Dataset rows have no field the API guarantees to be present or unique (the shape is defined by the+# Actor, not Apify), so there is no primary key to merge on. Combined with the lack of a server-side+# timestamp filter, the table is full-refresh only and the whole dataset is replaced on every sync.+PRIMARY_KEYS: dict[str, list[str] | None] = {+ DATASET_ITEMS_ENDPOINT: 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: [],+}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 c5a33331038f..d2d767e160cd 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@@ -1,30 +1,141 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.apify_dataset import (+ ApifyResumeConfig,+ apify_dataset_source,+ validate_credentials as validate_apify_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.settings import (+ 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 SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ApifyDatasetSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ApifyDatasetSource(SimpleSource[ApifyDatasetSourceConfig]):+class ApifyDatasetSource(ResumableSource[ApifyDatasetSourceConfig, ApifyResumeConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to render+ # in the public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.APIFYDATASET+ @property+ def connection_host_fields(self) -> list[str]:+ # dataset_id selects which Apify dataset the stored token reads from; changing it must+ # require re-entering the secret so a preserved token can't be retargeted at another dataset.+ return ["dataset_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.APIFY_DATASET,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Apify Dataset",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Apify API token and the ID of the dataset you want to import into the PostHog Data warehouse.++You can create an API token in your [Apify account settings](https://console.apify.com/settings/integrations), and find a dataset ID in the [Apify Console](https://console.apify.com/storage/datasets) (or use the `username~dataset-name` shorthand).++The token needs read access to the dataset's storage.""",iconPath="/static/services/apify_dataset.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/apify-dataset",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="apify_api_...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="dataset_id",+ label="Dataset ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="WkzbQMuFYuamGv3YF",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad/expired token or a token without access to the dataset surfaces as a requests+ # HTTPError when `_fetch_page` calls `raise_for_status()`. Retrying can't fix a credential+ # or addressing problem, so stop the sync. Match the stable status text + base host.+ "401 Client Error: Unauthorized for url: https://api.apify.com": "Your Apify API token is invalid or has expired. Create a new token in your Apify account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.apify.com": "Your Apify API token cannot access this dataset. Use a token with read access to the dataset's storage, then reconnect.",+ "404 Client Error: Not Found for url: https://api.apify.com": "The Apify dataset could not be found. Check that the dataset ID is correct and the token can access it.",+ }++ def get_schemas(+ self,+ config: ApifyDatasetSourceConfig,+ team_id: int,+ with_counts: bool = False,+ 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++ def validate_credentials(+ self, config: ApifyDatasetSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_apify_credentials(config.api_token, config.dataset_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ApifyResumeConfig]:+ return ResumableSourceManager[ApifyResumeConfig](inputs, ApifyResumeConfig)++ def source_for_pipeline(+ self,+ config: ApifyDatasetSourceConfig,+ resumable_source_manager: ResumableSourceManager[ApifyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return apify_dataset_source(+ api_token=config.api_token,+ dataset_id=config.dataset_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)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.pynew file mode 100644index 000000000000..48d0ec11155e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py@@ -0,0 +1,252 @@+from typing import Any++import pytest+from unittest import mock++import pyarrow as pa+import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset import apify_dataset+from 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,+)+++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 _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"])++[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+++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+++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 _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))++ manager.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))++ assert tables == []+++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"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.pynew file mode 100644index 000000000000..85fd640ff7d0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset_source.py@@ -0,0 +1,106 @@+import pytest+from unittest import mock++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.apify_dataset import (+ ApifyResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.source import ApifyDatasetSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ApifyDatasetSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> ApifyDatasetSourceConfig:+ return ApifyDatasetSourceConfig(api_token="apify_api_token", dataset_id="ds1")+++class TestApifyDatasetSource:+ def setup_method(self) -> None:+ self.source = ApifyDatasetSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.APIFYDATASET++ def test_source_config_basics(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Apify Dataset"+ assert config.iconPath == "/static/services/apify_dataset.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/apify-dataset"+ # Not hidden — a finished source ships visible, gated only by its alpha release status.+ assert getattr(config, "unreleasedSource", None) in (None, False)+ assert config.releaseStatus == "alpha"++ def test_source_config_fields(self) -> None:+ fields = {f.name: f for f in self.source.get_source_config.fields}+ assert set(fields) == {"api_token", "dataset_id"}+ api_token, dataset_id = fields["api_token"], fields["dataset_id"]+ assert isinstance(api_token, SourceFieldInputConfig)+ assert isinstance(dataset_id, SourceFieldInputConfig)+ assert api_token.required and api_token.secret+ assert dataset_id.required and not dataset_id.secret++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_connection_host_fields_includes_dataset_id(self) -> None:+ # dataset_id targets the stored token, so changing it must force re-entry of the secret.+ assert self.source.connection_host_fields == ["dataset_id"]++ def test_get_schemas_is_full_refresh_only(self) -> None:+ schemas = self.source.get_schemas(_config(), self.team_id)+ assert [s.name for s in schemas] == ["dataset_items"]+ schema = schemas[0]+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []+ assert schema.detected_primary_keys is None++ def test_get_schemas_filters_by_names(self) -> None:+ assert self.source.get_schemas(_config(), self.team_id, names=["nope"]) == []+ assert [s.name for s in self.source.get_schemas(_config(), self.team_id, names=["dataset_items"])] == [+ "dataset_items"+ ]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert len(tables) == 1+ assert tables[0]["name"] == "dataset_items"+ assert tables[0]["sync_methods"] == ["Full refresh"]++ @pytest.mark.parametrize("status", ["401", "403", "404"])+ def test_non_retryable_errors_cover_auth_and_addressing(self, status: str) -> None:+ keys = self.source.get_non_retryable_errors()+ assert any(status in key for key in keys)++ def test_validate_credentials_delegates_to_transport(self) -> None:+ with mock.patch.object(source_module, "validate_apify_credentials", return_value=(True, None)) as validate:+ ok, error = self.source.validate_credentials(_config(), self.team_id)+ assert ok is True and error is None+ validate.assert_called_once_with("apify_api_token", "ds1")++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ inputs = mock.Mock()+ inputs.logger = mock.Mock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ApifyResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = mock.Mock()+ inputs.schema_name = "dataset_items"+ inputs.logger = mock.Mock()+ 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)+ assert result is build.return_value+ build.assert_called_once_with(+ api_token="apify_api_token",+ dataset_id="ds1",+ endpoint="dataset_items",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 843b0dded63f..0074afd13eee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -266,7 +266,8 @@ class AmplitudeSourceConfig(config.Config):@config.configclass ApifyDatasetSourceConfig(config.Config):- pass+ api_token: str+ dataset_id: str@config.config