: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(warehouse_sources): add Apify run, actor, dataset and usage tables (#98317)
Tom Owers54a48e7b7cd9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 3936d8a86998..7cbce31fb88d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -315,14 +315,14 @@ Note: Admin API coverage of the identity objects is good. The three per-seat tab## ApifyDataset — **thin**-Today (1): `dataset_items`+Today (5): `actor_runs`, `actors`, `dataset_items`, `datasets`, `usage_monthly`Diffed against: <https://docs.apify.com/api/openapi.json>-- [ ] `GET /v2/actor-runs` — run history with status, duration and compute units - the operational and cost table for everything Apify does (high)-- [ ] `GET /v2/datasets` — dataset catalog lookup resolving the dataset IDs, item counts and owning actor for the items already synced (high)-- [ ] `GET /v2/actors` — actor lookup resolving the actId carried on runs and datasets (high)-- [ ] `GET /v2/users/me/usage/monthly` — monthly platform usage and spend breakdown (medium)+- [x] `GET /v2/actor-runs` — run history with status, duration and compute units - the operational and cost table for everything Apify does (high)+- [x] `GET /v2/datasets` — dataset catalog lookup resolving the dataset IDs, item counts and owning actor for the items already synced (high)+- [x] `GET /v2/actors` — actor lookup resolving the actId carried on runs and datasets (high)+- [x] `GET /v2/users/me/usage/monthly` — monthly platform usage and spend breakdown (medium)- [ ] `GET /v2/actor-tasks` — saved task definitions, the lookup between a schedule and the runs it produces (medium)- [ ] `GET /v2/datasets/{datasetId}/statistics` — per-field statistics for the dataset being synced (medium)- [ ] `GET /v2/actor-builds` — build history to correlate output changes with actor versions (low)@@ -330,7 +330,7 @@ Diffed against: <https://docs.apify.com/api/openapi.json>- [ ] `GET /v2/request-queues and /v2/actor-runs/{runId}/request-queue/requests` — crawl request state per run for coverage and failure analysis (low)- [ ] `GET /v2/key-value-stores/{storeId}/keys and /records` — non-dataset run outputs stored as key-value records (low)-Note: Deliberately scoped: the connector takes a single user-supplied dataset_id and syncs GET /v2/datasets/{id}/items into one user-named table, so it can cover any dataset but only one per configured source. It is not dynamic discovery - get_schemas returns the one configured endpoint. The rest of the Apify platform API (runs, actors, usage) is unreachable from this source, so the operational and cost side of Apify has no coverage at all.+Note: Deliberately scoped: the connector takes a single user-supplied dataset_id and syncs GET /v2/datasets/{id}/items into one user-named table, so it can cover any dataset but only one per configured source. It is not dynamic discovery - get_schemas returns a static endpoint catalog. The account-level tables alongside it (runs, actors, datasets, monthly usage) are addressed by the API token alone and cover the operational and cost side of the platform.## Apollo — gapsdiff --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 ce179ca679ed..0ee7ff7843f5 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,10 +1,16 @@-import dataclasses+from datetime import UTC, date, datetimefrom typing import Any, Optionalfrom urllib.parse import quote+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.settings import (APIFY_BASE_URL,+ DATASET_ITEMS_ENDPOINT,+ PLATFORM_ENDPOINTS,PRIMARY_KEYS,+ USAGE_MONTHLY_ENDPOINT,+ ApifyPlatformEndpointConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -13,22 +19,25 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (OffsetPaginator,+ SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-# 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.+# Rows per request. Both /datasets/{id}/items and the platform list endpoints cap `limit` at 1000,+# and they carry a high rate limit (~400 req/s), so a full page keeps the round-trip count down.PAGE_SIZE = 1000# 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"+@frozenclass 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.+ # Absolute offset of the next row to fetch. Dataset items are append-only and returned in stable+ # storage order, and the platform lists are sorted ascending by a creation timestamp, so an+ # offset points at the same row across requests — making it a safe resume cursor.offset: int = 0@@ -38,6 +47,92 @@ def _items_path(dataset_id: str) -> str:return f"/datasets/{quote(dataset_id, safe='')}/items"+def _to_iso8601(value: Any) -> Optional[str]:+ """Format an incremental cursor value for Apify's `startedAfter` filter, which takes an ISO 8601+ UTC datetime. Truncating to whole seconds only ever widens the window, so a row on the boundary+ is re-fetched and deduped on merge rather than skipped."""+ if value is None:+ return None+ if isinstance(value, datetime):+ utc = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _explode_usage_cycle(row: dict[str, Any]) -> list[dict[str, Any]]:+ """Turn the monthly usage response into one row per day of the usage cycle.++ The endpoint answers with a single object: the cycle's totals plus a `dailyServiceUsages` array.+ Day is the grain that makes spend queryable over time, so each day carries the cycle it belongs+ to and that cycle's credit totals.+ """+ cycle = row.get("usageCycle") or {}+ return [+ {+ **day,+ "usageCycleStartAt": cycle.get("startAt"),+ "usageCycleEndAt": cycle.get("endAt"),+ "totalUsageCreditsUsdBeforeVolumeDiscount": row.get("totalUsageCreditsUsdBeforeVolumeDiscount"),+ "totalUsageCreditsUsdAfterVolumeDiscount": row.get("totalUsageCreditsUsdAfterVolumeDiscount"),+ }+ for day in row.get("dailyServiceUsages") or []+ if isinstance(day, dict)+ ]+++def _platform_resource(name: str, config: ApifyPlatformEndpointConfig, use_incremental: bool) -> EndpointResource:+ params: dict[str, Any] = dict(config.params)+ if use_incremental and config.incremental_param:+ params[config.incremental_param] = {+ "type": "incremental",+ "cursor_path": config.incremental_cursor,+ "initial_value": None,+ "convert": _to_iso8601,+ }++ paginator = (+ OffsetPaginator(limit=PAGE_SIZE, total_path=config.total_path) if config.paginated else SinglePagePaginator()+ )++ resource: EndpointResource = {+ "name": name,+ "table_name": name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": {+ "path": config.path,+ "params": params,+ "paginator": paginator,+ "data_selector": config.data_selector,+ # Apify documents the envelope key as always present, so a response without it is a+ # shape change — fail loud instead of syncing zero rows.+ "data_selector_required": True,+ },+ "table_format": "delta",+ }++ if name == USAGE_MONTHLY_ENDPOINT:+ resource["data_map"] = _explode_usage_cycle++ return resource+++def _dataset_items_resource(name: str, dataset_id: str) -> EndpointResource:+ return {+ "name": name,+ "endpoint": {+ "path": _items_path(dataset_id),+ "params": {"format": "json"},+ # 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),+ # 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,+ },+ }++def apify_dataset_source(api_token: str,dataset_id: str,@@ -46,31 +141,32 @@ def apify_dataset_source(job_id: str,resumable_source_manager: ResumableSourceManager[ApifyResumeConfig],db_incremental_field_last_value: Optional[Any] = None,+ should_use_incremental_field: bool = False,) -> SourceResponse:+ platform_config = PLATFORM_ENDPOINTS.get(endpoint)+ if platform_config is not None:+ use_incremental = should_use_incremental_field and platform_config.incremental_param is not None+ resource_config = _platform_resource(endpoint, platform_config, use_incremental)+ # A single-page endpoint has no cursor to come back to.+ resumable = platform_config.paginated+ elif endpoint == DATASET_ITEMS_ENDPOINT:+ use_incremental = False+ resource_config = _dataset_items_resource(endpoint, dataset_id)+ resumable = True+ else:+ raise ValueError(f"Unknown Apify endpoint: {endpoint}")+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,- },- }- ],+ "resources": [resource_config],}initial_paginator_state: Optional[dict[str, Any]] = None- if resumable_source_manager.can_resume():+ if resumable and resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()if resume is not None:initial_paginator_state = {"offset": resume.offset}@@ -83,16 +179,25 @@ def apify_dataset_source(rest_config,team_id,job_id,- db_incremental_field_last_value,- resume_hook=save_checkpoint,+ db_incremental_field_last_value if use_incremental else None,+ resume_hook=save_checkpoint if resumable else None,initial_paginator_state=initial_paginator_state,)+ partition_key = platform_config.partition_key if platform_config else Nonereturn SourceResponse(name=endpoint,items=lambda: resource,primary_keys=PRIMARY_KEYS.get(endpoint),column_hints=resource.column_hints,+ # Every platform list endpoint sorts ascending by its creation timestamp unless `desc=1` is+ # passed, and dataset items come back in storage (append) order.+ sort_mode="asc",+ partition_count=1 if partition_key else None,+ partition_size=1 if partition_key else None,+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/canonical_descriptions.pynew file mode 100644index 000000000000..dfd3eefcd7dc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/canonical_descriptions.py@@ -0,0 +1,74 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# `dataset_items` ships no entry: its columns are whatever the Actor stored, so there is nothing+# fixed to describe.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "actor_runs": {+ "description": "One row per Actor run on the account, with its status, timings, compute cost and the storages it wrote.",+ "docs_url": "https://docs.apify.com/api/v2/actor-runs-get",+ "columns": {+ "id": "Unique identifier of the run.",+ "actId": "Identifier of the Actor that was run. Joins to the actors table.",+ "userId": "Identifier of the user who owns the run.",+ "actorTaskId": "Identifier of the saved Actor task the run came from, or null when the Actor was run directly.",+ "status": "Lifecycle status of the run, such as READY, RUNNING, SUCCEEDED, FAILED, TIMED-OUT or ABORTED.",+ "startedAt": "Time the run started.",+ "finishedAt": "Time the run finished, or null while it is still running.",+ "buildId": "Identifier of the Actor build the run executed.",+ "buildNumber": "Version of the Actor build the run executed, such as 0.1.1.",+ "meta": "Origin of the run, plus the schedule that started it when it was scheduled.",+ "usageTotalUsd": "Total cost of the run in US dollars. Hidden when the request is not authenticated.",+ "defaultDatasetId": "Identifier of the dataset the run stored its output in. Joins to the datasets table.",+ "defaultKeyValueStoreId": "Identifier of the key-value store the run wrote non-dataset output to.",+ "defaultRequestQueueId": "Identifier of the request queue the run crawled from.",+ },+ },+ "actors": {+ "description": "The Actors the account created or used, with build and run counts.",+ "docs_url": "https://docs.apify.com/api/v2/actors-get",+ "columns": {+ "id": "Unique identifier of the Actor. Matches actId on runs and datasets.",+ "createdAt": "Time the Actor was created.",+ "modifiedAt": "Time the Actor was last modified.",+ "name": "Technical name of the Actor, unique within its owner.",+ "username": "Username of the account that owns the Actor.",+ "title": "Human-readable name of the Actor.",+ "stats": "Aggregate counts for the Actor, including total builds, total runs, user counts over trailing windows and the time it last ran.",+ },+ },+ "datasets": {+ "description": "The account's datasets, including the unnamed ones an Actor run creates, with item counts and the run that produced them.",+ "docs_url": "https://docs.apify.com/api/v2/datasets-get",+ "columns": {+ "id": "Unique identifier of the dataset. This is the value the dataset_items table is configured with.",+ "name": "Name of the dataset. Datasets created by an Actor run are unnamed.",+ "userId": "Identifier of the user who owns the dataset.",+ "createdAt": "Time the dataset was created.",+ "modifiedAt": "Time the dataset was last written to.",+ "accessedAt": "Time the dataset was last read.",+ "itemCount": "Number of items stored in the dataset. Takes up to 5 seconds to catch up after a write.",+ "cleanItemCount": "Number of items excluding empty and hidden ones. Takes up to 5 seconds to catch up after a write.",+ "actId": "Identifier of the Actor whose run created the dataset, or null when it was created directly. Joins to the actors table.",+ "actRunId": "Identifier of the run that created the dataset, or null when it was created directly. Joins to the actor_runs table.",+ "title": "Human-readable name of the dataset.",+ "username": "Username of the account that owns the dataset.",+ "generalAccess": "Whether the dataset is restricted to its owner or readable more widely.",+ "stats": "Read and write counts for the dataset, plus its stored and uncompressed size in bytes.",+ },+ },+ "usage_monthly": {+ "description": "Platform usage and spend for the current monthly usage cycle, one row per day. The whole cycle is re-imported on every sync.",+ "docs_url": "https://docs.apify.com/api/v2/users-me-usage-monthly-get",+ "columns": {+ "date": "Day the usage was recorded on.",+ "serviceUsage": "Usage for that day, keyed by service name such as ACTOR_COMPUTE_UNITS.",+ "totalUsageCreditsUsd": "Total spend for that day in US dollars.",+ "usageCycleStartAt": "Start of the monthly usage cycle the day belongs to.",+ "usageCycleEndAt": "End of the monthly usage cycle the day belongs to.",+ "totalUsageCreditsUsdBeforeVolumeDiscount": "Spend for the whole cycle in US dollars, before any volume discount. Repeated on every day of the cycle.",+ "totalUsageCreditsUsdAfterVolumeDiscount": "Spend for the whole cycle in US dollars, after any volume discount. Repeated on every day of the cycle.",+ },+ },+}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 c79c865cdf3b..7ed92c205a5c 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@@ -1,23 +1,95 @@+from dataclasses import field+from typing import Any, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_fieldfrom products.warehouse_sources.backend.types import IncrementalFieldAPIFY_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.+# rows are arbitrary Actor output, so this table's columns are whatever the Actor stored.DATASET_ITEMS_ENDPOINT = "dataset_items"-ENDPOINTS = (DATASET_ITEMS_ENDPOINT,)+# The rest of the tables are account-level: they are addressed by the API token alone and describe+# the whole Apify account rather than the one configured dataset — the runs it has executed, the+# Actors and datasets those runs reference, and what the account has spent.+ACTOR_RUNS_ENDPOINT = "actor_runs"+ACTORS_ENDPOINT = "actors"+DATASETS_ENDPOINT = "datasets"+USAGE_MONTHLY_ENDPOINT = "usage_monthly"++ENDPOINTS = (+ DATASET_ITEMS_ENDPOINT,+ ACTOR_RUNS_ENDPOINT,+ ACTORS_ENDPOINT,+ DATASETS_ENDPOINT,+ USAGE_MONTHLY_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,+ ACTOR_RUNS_ENDPOINT: ["id"],+ ACTORS_ENDPOINT: ["id"],+ DATASETS_ENDPOINT: ["id"],+ # One row per day of a usage cycle, and a day belongs to exactly one cycle.+ USAGE_MONTHLY_ENDPOINT: ["date"],+}++# Only `/actor-runs` carries a server-side lower-bound filter (`startedAfter`), so it is the only+# table that can sync incrementally. The others page their full collection every run, and dataset+# items have no timestamp at all — leaving an endpoint out of this map keeps `build_endpoint_schemas`+# from advertising incremental sync for it.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ ACTOR_RUNS_ENDPOINT: [incremental_field("startedAt")],}-# 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 —-# leaving the endpoint out of the map keeps `build_endpoint_schemas` from advertising incremental sync.-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}++@frozen+class ApifyPlatformEndpointConfig:+ path: str+ # Every platform list endpoint answers `{"data": {"items": [...], "total": N, ...}}`.+ data_selector: str = "data.items"+ total_path: Optional[str] = "data.total"+ paginated: bool = True+ params: dict[str, Any] = field(default_factory=dict)+ # Stable creation-time field to partition on. Never a field that can move (`modifiedAt`,+ # `accessedAt`, `stats.lastRunStartedAt`), which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ # Query param that filters the collection to rows at or after a timestamp, and the field it+ # filters on. Set only where Apify documents a real server-side filter.+ incremental_param: Optional[str] = None+ incremental_cursor: Optional[str] = None+++PLATFORM_ENDPOINTS: dict[str, ApifyPlatformEndpointConfig] = {+ ACTOR_RUNS_ENDPOINT: ApifyPlatformEndpointConfig(+ path="/actor-runs",+ partition_key="startedAt",+ incremental_param="startedAfter",+ incremental_cursor="startedAt",+ ),+ ACTORS_ENDPOINT: ApifyPlatformEndpointConfig(+ path="/actors",+ partition_key="createdAt",+ ),+ DATASETS_ENDPOINT: ApifyPlatformEndpointConfig(+ path="/datasets",+ # An Actor run stores its output in an unnamed dataset, and those are the datasets whose+ # rows `dataset_items` syncs. The endpoint lists only named datasets unless asked.+ params={"unnamed": "true"},+ partition_key="createdAt",+ ),+ USAGE_MONTHLY_ENDPOINT: ApifyPlatformEndpointConfig(+ path="/users/me/usage/monthly",+ # A single object holding the cycle totals and a daily breakdown, not a paginated list.+ data_selector="data",+ total_path=None,+ paginated=False,+ ),+}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 34c5f3158ae0..4bd3b0c96b65 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@@ -15,11 +15,18 @@ 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 (+ ACTOR_RUNS_ENDPOINT,+ ACTORS_ENDPOINT,DATASET_ITEMS_ENDPOINT,+ DATASETS_ENDPOINT,ENDPOINTS,INCREMENTAL_FIELDS,+ USAGE_MONTHLY_ENDPOINT,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from 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 ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (@@ -64,7 +71,7 @@ class ApifyDatasetSource(ResumableSource[ApifyDatasetSourceConfig, ApifyResumeCoYou 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.""",+The token needs read access to the dataset's storage. The account-level tables (runs, Actors, datasets and monthly usage) come from the same token.""",iconPath="/static/services/apify_dataset.png",docsUrl="https://posthog.com/docs/cdp/sources/apify-dataset",fields=cast(@@ -114,10 +121,21 @@ The token needs read access to the dataset's storage.""",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."+ 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.",+ ACTOR_RUNS_ENDPOINT: "Every Actor run on the account, with its status, timings, compute usage and the storages it wrote. Syncs incrementally on the run start time.",+ ACTORS_ENDPOINT: "The Actors the account has created or used, with build and run counts. Resolves the actor ID carried on runs and datasets. Full refresh only.",+ DATASETS_ENDPOINT: "The account's datasets, including the unnamed ones an Actor run creates, with item counts and the run that produced them. Full refresh only.",+ USAGE_MONTHLY_ENDPOINT: "Platform usage and spend for the current monthly cycle, one row per day. Full refresh only: the cycle is re-imported on every sync.",},)+ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS+def validate_credentials(self,config: ApifyDatasetSourceConfig,@@ -143,5 +161,6 @@ The token needs read access to the dataset's storage.""",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+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,+ should_use_incremental_field=inputs.should_use_incremental_field,)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 12a8dfacf922..c3d2eba7bbcd 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,4 +1,5 @@import json+from datetime import UTC, datetimefrom typing import Anyimport pytest@@ -12,6 +13,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataapify_dataset_source,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.settings import (+ ACTOR_RUNS_ENDPOINT,+ ACTORS_ENDPOINT,+ DATASETS_ENDPOINT,+ USAGE_MONTHLY_ENDPOINT,+)CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"APIFY_SESSION_PATCH = (@@ -63,6 +70,30 @@ def _run(manager, responses):)+def _platform_response(items: Any, total: int | None = None) -> Response:+ """Shape of every Apify platform list endpoint: rows wrapped in a data envelope."""+ return _response({"data": {"items": items, "total": total if total is not None else len(items)}})+++def _run_platform(+ endpoint: str,+ manager,+ *,+ db_incremental_field_last_value: Any = None,+ should_use_incremental_field: bool = False,+):+ return apify_dataset_source(+ api_token="tok",+ dataset_id="ds1",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )++class TestPagination:@mock.patch.object(apify_dataset, "PAGE_SIZE", 2)@mock.patch(CLIENT_SESSION_PATCH)@@ -143,3 +174,113 @@ class TestValidateCredentials:ok, msg = validate_credentials("tok", "ds1")assert ok is Falseassert "reach the Apify API" in (msg or "")+++class TestPlatformEndpoints:+ @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_pages_on_envelope_total_and_checkpoints_offset(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _platform_response([{"id": "a"}, {"id": "b"}], total=3),+ _platform_response([{"id": "c"}], total=3),+ ],+ )++ manager = _make_manager()+ rows = _rows(_run_platform(ACTOR_RUNS_ENDPOINT, manager))++ assert [r["id"] for r in rows] == ["a", "b", "c"]+ assert [p["offset"] for p in params] == [0, 2]+ assert manager.save_state.call_args.args[0] == ApifyResumeConfig(offset=2)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_sends_started_after_from_watermark(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_platform_response([])])++ _rows(+ _run_platform(+ ACTOR_RUNS_ENDPOINT,+ _make_manager(),+ db_incremental_field_last_value=datetime(2026, 3, 4, 5, 6, 7, 890000, tzinfo=UTC),+ should_use_incremental_field=True,+ )+ )++ # Truncated to whole seconds, which only ever re-fetches the boundary row.+ assert params[0]["startedAfter"] == "2026-03-04T05:06:07Z"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_omits_the_watermark(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_platform_response([])])++ _rows(+ _run_platform(+ ACTOR_RUNS_ENDPOINT,+ _make_manager(),+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ )++ assert "startedAfter" not in params[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_datasets_asks_for_unnamed_storages(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_platform_response([])])++ _rows(_run_platform(DATASETS_ENDPOINT, _make_manager()))++ # Actor runs store their output in unnamed datasets, which the endpoint hides by default.+ assert params[0]["unnamed"] == "true"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_envelope_raises_loudly(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"error": {"type": "insufficient-permissions"}})])++ with pytest.raises(ValueError, match="matched nothing"):+ _rows(_run_platform(ACTORS_ENDPOINT, _make_manager()))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_monthly_usage_becomes_one_row_per_day(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(+ {+ "data": {+ "usageCycle": {"startAt": "2026-03-01T00:00:00.000Z", "endAt": "2026-03-31T23:59:59.999Z"},+ "monthlyServiceUsage": {"ACTOR_COMPUTE_UNITS": {"quantity": 3}},+ "dailyServiceUsages": [+ {"date": "2026-03-01", "serviceUsage": {}, "totalUsageCreditsUsd": 0.5},+ {"date": "2026-03-02", "serviceUsage": {}, "totalUsageCreditsUsd": 1.5},+ ],+ "totalUsageCreditsUsdBeforeVolumeDiscount": 2.5,+ "totalUsageCreditsUsdAfterVolumeDiscount": 2.0,+ }+ }+ )+ ],+ )++ manager = _make_manager()+ rows = _rows(_run_platform(USAGE_MONTHLY_ENDPOINT, manager))++ assert [r["date"] for r in rows] == ["2026-03-01", "2026-03-02"]+ assert [r["totalUsageCreditsUsd"] for r in rows] == [0.5, 1.5]+ assert rows[0]["usageCycleStartAt"] == "2026-03-01T00:00:00.000Z"+ assert rows[0]["usageCycleEndAt"] == "2026-03-31T23:59:59.999Z"+ assert rows[0]["totalUsageCreditsUsdAfterVolumeDiscount"] == 2.0+ # A single object endpoint has no cursor, so nothing is checkpointed.+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ def test_unknown_endpoint_raises(self) -> None:+ with pytest.raises(ValueError, match="Unknown Apify endpoint"):+ _run_platform("not_a_table", _make_manager())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.pyindex 9bb62b1b73e3..bbf465f87810 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py@@ -38,7 +38,7 @@ DESCRIPTIONS_NOT_IN_SCHEMAS = {# Static-catalog sources with no curated descriptions at all: every table falls back to LLM# enrichment. Adding descriptions is an improvement, so drop the entry when one does.-SOURCES_WITHOUT_CURATED_DESCRIPTIONS = {"ActiveCampaign", "Airtable", "ApifyDataset", "PgAnalyze"}+SOURCES_WITHOUT_CURATED_DESCRIPTIONS = {"ActiveCampaign", "Airtable", "PgAnalyze"}CREDENTIAL_FIELD = re.compile(r"api[_-]?key|access[_-]?key|token|secret|password|passphrase|private[_-]?key", re.I)