Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement appstack import source (#72642)

Tom Owers0bc026d7314d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index bbdf790f453f..04c540413563 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -65,6 +65,7 @@ the row lists both.
| appfollow | HTTP | requests | ✅ |
| appsflyer | HTTP (CSV reports) | requests | ✅ |
| appsignal | HTTP (REST + GraphQL) | requests | ✅ |
+| appstack | HTTP | requests + `rest_source.RESTClient` | ✅ |
| argocd | HTTP | requests | ✅ |
| asana | HTTP | requests | ✅ |
| ashby | HTTP | requests | ✅ |
@@ -666,7 +667,6 @@ doesn't conflict with concurrent PRs.
- amazon_sqs
- appcues
- apple_search_ads
-- appstack
- apptivo
- appwrite
- asknicely
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/appstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/appstack.py
new file mode 100644
index 000000000000..be62edd60c1e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/appstack.py
@@ -0,0 +1,180 @@
+import dataclasses
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.settings import (
+ APPSTACK_API_BASE_URL,
+ APPSTACK_ENDPOINTS,
+ PAGE_SIZE,
+)
+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.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+VALIDATION_PROBE_WINDOW_SECONDS = 24 * 60 * 60
+
+
+class AppstackResumeConfig:
+ # Next `offset` to request, as reported by the paginator after the last yielded page.
+ offset: int
+ # The export window's `timestamp` param, pinned at walk start. Offsets are positions within
+ # one window, so a resumed attempt must replay the exact same window rather than re-deriving
+ # it from a watermark that advanced while the walk ran.
+ window_start: int
+
+
+def _to_unix_seconds(value: Any) -> int:
+ """Coerce an incremental watermark (datetime, date, epoch number, or string) to Unix seconds."""
+ if isinstance(value, datetime):
+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return max(0, int(utc_dt.timestamp()))
+ if isinstance(value, date):
+ return _to_unix_seconds(datetime.combine(value, datetime.min.time(), tzinfo=UTC))
+ if isinstance(value, int | float):
+ return max(0, int(value))
+ if isinstance(value, str):
+ try:
+ return _to_unix_seconds(datetime.fromisoformat(value.replace("Z", "+00:00")))
+ except ValueError:
+ pass
+ try:
+ return max(0, int(float(value)))
+ except ValueError:
+ return 0
+ return 0
+
+
+def _export_window_start(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> int:
+ """`timestamp` (Unix seconds) the export window starts at.
+
+ The param is required, so a full refresh (or first incremental sync with no watermark yet)
+ passes 0 to export the app's full history. The pipeline already shifts the watermark back by
+ the schema's lookback window before it reaches this function.
+ """
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ return _to_unix_seconds(db_incremental_field_last_value)
+ return 0
+
+
+def get_resource(name: str, should_use_incremental_field: bool, window_start: int) -> EndpointResource:
+ cfg = APPSTACK_ENDPOINTS[name]
+
+ return {
+ "name": cfg.name,
+ "table_name": cfg.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ "data_selector": "data",
+ "path": cfg.path,
+ "params": {"timestamp": window_start},
+ },
+ # Parse ISO 8601 event_time strings into real timestamps so the incremental watermark and
+ # the datetime partition key operate on a datetime column.
+ "columns": {"event_time": {"data_type": "timestamp"}},
+ "table_format": "delta",
+ }
+
+
+def appstack_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AppstackResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+) -> SourceResponse:
+ cfg = APPSTACK_ENDPOINTS[endpoint]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resume is not None:
+ window_start = resume.window_start
+ initial_paginator_state = {"offset": resume.offset}
+ else:
+ window_start = _export_window_start(should_use_incremental_field, db_incremental_field_last_value)
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": APPSTACK_API_BASE_URL,
+ # Appstack expects the raw API key in the Authorization header, no Bearer prefix.
+ "auth": {
+ "type": "api_key",
+ "name": "Authorization",
+ "location": "header",
+ "api_key": api_key,
+ },
+ # The response's `total_count` counts the current page, not the whole window, so it
+ # must never be used as a grand total; the walk ends when a page comes back short.
+ "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None),
+ # Export rows can carry device/user identifiers (idfv, maid, customer_user_id) the
+ # name-based sample scrubbers don't recognise, so keep response bodies out of shared
+ # HTTP sample storage. Requests are still metered and logged (with the key redacted).
+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),
+ },
+ "resource_defaults": None,
+ "resources": [get_resource(endpoint, should_use_incremental_field, window_start)],
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Called after each yielded page; persist only while a next page exists (the Redis TTL
+ # cleans up on completion). A crash re-yields the last page and merge dedupes on the
+ # primary key rather than skipping rows.
+ if state and state.get("offset") is not None:
+ resumable_source_manager.save_state(
+ AppstackResumeConfig(offset=int(state["offset"]), window_start=window_start)
+ )
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=cfg.primary_keys,
+ column_hints=resource.column_hints,
+ # Documented: exports are ordered by event_time ascending.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if cfg.partition_key else None,
+ partition_format="month" if cfg.partition_key else None,
+ partition_keys=[cfg.partition_key] if cfg.partition_key else None,
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Cheap one-row probe against GET /export to confirm the API key is genuine.
+
+ Returns False only for auth failures (401/403). Transient or unexpected statuses (429,
+ 5xx, ...) are raised via `raise_for_status()` so they surface as a real error rather than
+ being misreported to the user as an invalid API key.
+ """
+ window_start = int(datetime.now(UTC).timestamp()) - VALIDATION_PROBE_WINDOW_SECONDS
+ response = make_tracked_session(capture=False, redact_values=(api_key,)).get(
+ f"{APPSTACK_API_BASE_URL}/export",
+ params={"timestamp": window_start, "limit": 1},
+ headers={"Authorization": api_key},
+ timeout=30,
+ )
+ if response.status_code in (401, 403):
+ return False
+ response.raise_for_status()
+ return True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/canonical_descriptions.py
new file mode 100644
index 000000000000..4d3447d489cc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/canonical_descriptions.py
@@ -0,0 +1,38 @@
+# Curated from the official Appstack Exports API reference: https://docs.appstack.tech/api/export
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "Attributed events for the connected app: installs and in-app events matched to the ad campaigns that drove them, one row per event.",
+ "docs_url": "https://docs.appstack.tech/api/export",
+ "columns": {
+ "event_id": "Unique identifier for the event.",
+ "event_time": "When the event occurred (ISO 8601). Exports are ordered by this field ascending.",
+ "event_name": "Name of the event, prefixed by Appstack (e.g. appstack_purchase).",
+ "appstack_id": "Appstack's identifier for the device/user the event belongs to.",
+ "media_source": "Ad network or media source the event is attributed to.",
+ "campaign_id": "Identifier of the attributed campaign.",
+ "campaign_name": "Name of the attributed campaign.",
+ "adset_id": "Identifier of the attributed ad set.",
+ "adset_name": "Name of the attributed ad set.",
+ "ad_id": "Identifier of the attributed ad.",
+ "ad_name": "Name of the attributed ad.",
+ "matching_type": "How the event was matched to the ad interaction: network or geo.",
+ "click_to_first_open_hours": "Hours between the ad click and the app's first open.",
+ "confidence_score": "Confidence of the attribution match: low, medium, or high.",
+ "country": "Country of the device (ISO 3166-1 alpha-2).",
+ "os": "Device operating system: ios or android.",
+ "app_id": "Identifier of the app the event belongs to.",
+ "app_name": "Name of the app the event belongs to.",
+ "install_type": "iOS only: new_install or reinstall_same_device.",
+ "revenue": "Revenue amount attached to the event, in the original currency; null for non-revenue events.",
+ "currency": "Currency of the revenue amount (ISO 4217).",
+ "revenue_usd": "Revenue converted to USD at the event-date exchange rate; null for non-revenue events.",
+ "idfv": "iOS identifier for vendor, when available.",
+ "maid": "Mobile advertising ID (GAID or IDFA), when available.",
+ "customer_user_id": "Your own user identifier for the device/user, when set in the SDK.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/settings.py
new file mode 100644
index 000000000000..060d5369d166
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/settings.py
@@ -0,0 +1,47 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+APPSTACK_API_BASE_URL = "https://api.appstack.tech/api/v1"
+
+# Documented default and maximum page size for GET /export (`limit` is 1-10000).
+PAGE_SIZE = 10000
+
+# Attribution events can surface in the export after their event_time (late postbacks, delayed
+# matching), so each incremental run re-reads a trailing window; merge dedupes on event_id. The
+# publication delay is undocumented, so a full day is a conservative default.
+DEFAULT_INCREMENTAL_LOOKBACK_SECONDS = 24 * 60 * 60
+
+
+@dataclass
+class AppstackEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime field to partition by — an event's time never changes after export.
+ partition_key: Optional[str] = None
+
+
+# Appstack's whole public data surface is one endpoint: GET /export returns the app's attributed
+# events (installs and in-app events matched to the ad campaigns that drove them), ordered by
+# event_time ascending, paged with limit/offset within a window starting at the required
+# `timestamp` param (Unix seconds). API keys are scoped to a single app, so one source connection
+# covers one app.
+APPSTACK_ENDPOINTS: dict[str, AppstackEndpointConfig] = {
+ "events": AppstackEndpointConfig(
+ name="events",
+ path="/export",
+ primary_keys=["event_id"],
+ partition_key="event_time",
+ incremental_fields=[incremental_field("event_time")],
+ ),
+}
+
+ENDPOINTS = tuple(APPSTACK_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in APPSTACK_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/source.py
index 0209a9d666ad..c830e044eec9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/source.py
@@ -1,13 +1,40 @@
-from typing import cast
+from typing import Optional, cast
+
+import requests
from 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.appstack.appstack import (
+ AppstackResumeConfig,
+ appstack_source,
+ validate_credentials as validate_appstack_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.settings import (
+ DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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 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 (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appstack import (
AppstackSourceConfig,
)
@@ -15,7 +42,10 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AppstackSource(SimpleSource[AppstackSourceConfig]):
+class AppstackSource(ResumableSource[AppstackSourceConfig, AppstackResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.appstack.tech/api/export"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.APPSTACK
@@ -25,9 +55,102 @@ class AppstackSource(SimpleSource[AppstackSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.APPSTACK,
category=DataWarehouseSourceCategory.ADVERTISING,
- keywords=["mobile attribution"],
+ keywords=["mobile attribution", "mmp", "ad attribution"],
label="Appstack",
+ caption="""Enter your Appstack API key to pull your attributed mobile events into the PostHog Data warehouse.
+
+You can find the API key in your Appstack dashboard settings. API keys are scoped to a single app, so add one source per app.""",
iconPath="/static/services/appstack.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/appstack",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.appstack.tech": "Appstack rejected the API key. Copy the current API key for this app from your Appstack dashboard settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.appstack.tech": "Appstack denied access with this API key. Check that the key belongs to the app you want to sync, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AppstackSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ # The incremental lookback re-reads a trailing window each run, so append syncs would
+ # duplicate the overlap; only merge dedupes it.
+ merge_only=ENDPOINTS,
+ descriptions={
+ "events": (
+ "Attributed events for the connected app: installs and in-app events matched "
+ "to the ad campaigns that drove them"
+ ),
+ },
+ )
+ for schema in schemas:
+ schema.default_incremental_lookback_seconds = DEFAULT_INCREMENTAL_LOOKBACK_SECONDS
+ return schemas
+
+ def validate_credentials(
+ self, config: AppstackSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ if validate_appstack_credentials(config.api_key):
+ return True, None
+ return (
+ False,
+ "Appstack rejected the API key. Copy the current API key for this app from your Appstack dashboard settings.",
+ )
+ except requests.RequestException:
+ # A rate-limit, 5xx, or network blip isn't a bad credential — don't mislabel it.
+ return (
+ False,
+ "Could not reach Appstack to validate the API key. This may be a temporary issue — please try again.",
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppstackResumeConfig]:
+ return ResumableSourceManager[AppstackResumeConfig](inputs, AppstackResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AppstackSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AppstackResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return appstack_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py
new file mode 100644
index 000000000000..bea60cf2b04b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py
@@ -0,0 +1,230 @@
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack import (
+ AppstackResumeConfig,
+ _export_window_start,
+ _to_unix_seconds,
+ appstack_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.settings import PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class TestToUnixSeconds:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), 1772593094),
+ ("naive_datetime_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), 1772593094),
+ ("date_value", date(2026, 3, 4), 1772582400),
+ ("epoch_int", 1772593094, 1772593094),
+ ("epoch_float", 1772593094.9, 1772593094),
+ ("iso_string", "2026-03-04T02:58:14+00:00", 1772593094),
+ ("iso_string_z_suffix", "2026-03-04T02:58:14Z", 1772593094),
+ ("epoch_string", "1772593094", 1772593094),
+ ("garbage_string", "not-a-timestamp", 0),
+ ("negative_epoch_clamped", -5, 0),
+ ]
+ )
+ def test_conversion(self, _label: str, value: Any, expected: int) -> None:
+ assert _to_unix_seconds(value) == expected
+
+
+class TestExportWindowStart:
+ @parameterized.expand(
+ [
+ # Full refresh must always export the full history regardless of any stored watermark.
+ ("full_refresh_ignores_watermark", False, datetime(2026, 3, 4, tzinfo=UTC), 0),
+ # First incremental sync has no watermark yet and also backfills everything.
+ ("incremental_without_watermark", True, None, 0),
+ ("incremental_with_watermark", True, datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), 1772593094),
+ ]
+ )
+ def test_window_start(self, _label: str, incremental: bool, last_value: Any, expected: int) -> None:
+ assert _export_window_start(incremental, last_value) == expected
+
+
+class TestGetResource:
+ @staticmethod
+ def _params(resource: Any) -> dict[str, Any]:
+ return cast(dict[str, Any], cast(dict[str, Any], resource["endpoint"])["params"])
+
+ def test_full_refresh_resource_shape(self) -> None:
+ resource = get_resource("events", should_use_incremental_field=False, window_start=0)
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+
+ assert resource["name"] == "events"
+ assert resource["write_disposition"] == "replace"
+ assert resource["table_format"] == "delta"
+ assert endpoint["path"] == "/export"
+ assert endpoint["data_selector"] == "data"
+ # `timestamp` is required by the API even on a full refresh.
+ assert self._params(resource)["timestamp"] == 0
+
+ def test_incremental_resource_merges_and_windows(self) -> None:
+ resource = get_resource("events", should_use_incremental_field=True, window_start=1772593094)
+
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ assert self._params(resource)["timestamp"] == 1772593094
+
+ def test_event_time_parsed_as_timestamp(self) -> None:
+ # Without this hint event_time stays an ISO string and the incremental watermark and
+ # datetime partitioning silently break.
+ resource = get_resource("events", should_use_incremental_field=True, window_start=0)
+ columns = cast(dict[str, Any], resource["columns"])
+ assert columns["event_time"]["data_type"] == "timestamp"
+
+
+class TestAppstackSource:
+ def _manager(self, *, can_resume: bool, state: AppstackResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = state
+ return manager
+
+ def _call(self, manager: MagicMock, **kwargs: Any) -> Any:
+ defaults: dict[str, Any] = {
+ "api_key": "key",
+ "endpoint": "events",
+ "team_id": 1,
+ "job_id": "job",
+ "resumable_source_manager": manager,
+ "db_incremental_field_last_value": None,
+ "should_use_incremental_field": False,
+ }
+ defaults.update(kwargs)
+ return appstack_source(**defaults)
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
+ def test_source_response_fields(self, mock_rest: MagicMock) -> None:
+ mock_resource = MagicMock()
+ mock_resource.name = "events"
+ mock_resource.column_hints = {"event_time": "timestamp"}
+ mock_rest.return_value = mock_resource
+
+ response = self._call(self._manager(can_resume=False))
+
+ assert response.name == "events"
+ assert response.primary_keys == ["event_id"]
+ # Documented: exports are ordered by event_time ascending.
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["event_time"]
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
+ def test_paginator_never_trusts_total_count(self, mock_rest: MagicMock) -> None:
+ # Appstack's `total_count` counts the current page, not the whole window; a paginator
+ # reading it as a grand total would stop after the first page and silently truncate.
+ mock_rest.return_value = MagicMock(name="events", column_hints=None)
+
+ self._call(self._manager(can_resume=False))
+
+ paginator = mock_rest.call_args.args[0]["client"]["paginator"]
+ assert paginator.total_path is None
+ assert paginator.limit == PAGE_SIZE
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
+ def test_client_session_disables_sample_capture(self, mock_rest: MagicMock, mock_session: MagicMock) -> None:
+ # Export rows carry device/user identifiers the sample scrubbers can't recognise; the client
+ # must run on a capture=False session so response bodies stay out of shared sample storage.
+ mock_rest.return_value = MagicMock(name="events", column_hints=None)
+
+ self._call(self._manager(can_resume=False))
+
+ assert mock_session.call_args.kwargs["capture"] is False
+ assert mock_rest.call_args.args[0]["client"]["session"] is mock_session.return_value
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
+ def test_resume_replays_pinned_window_at_saved_offset(self, mock_rest: MagicMock) -> None:
+ # Offsets are positions within one export window: a resumed attempt must reuse the saved
+ # window's `timestamp`, not re-derive it from a watermark that advanced mid-walk.
+ mock_rest.return_value = MagicMock(name="events", column_hints=None)
+ manager = self._manager(can_resume=True, state=AppstackResumeConfig(offset=30000, window_start=1772593094))
+
+ self._call(
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+
+ config = mock_rest.call_args.args[0]
+ params = config["resources"][0]["endpoint"]["params"]
+ assert params["timestamp"] == 1772593094
+ assert mock_rest.call_args.kwargs["initial_paginator_state"] == {"offset": 30000}
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
+ def test_resume_hook_saves_offset_with_window(self, mock_rest: MagicMock) -> None:
+ mock_rest.return_value = MagicMock(name="events", column_hints=None)
+ manager = self._manager(can_resume=False)
+
+ self._call(
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+
+ resume_hook = mock_rest.call_args.kwargs["resume_hook"]
+
+ # A page with a next offset persists the checkpoint together with its window.
+ resume_hook({"offset": 20000})
+ manager.save_state.assert_called_once_with(AppstackResumeConfig(offset=20000, window_start=1772593094))
+
+ # A terminal page (no resume state) saves nothing.
+ manager.save_state.reset_mock()
+ resume_hook(None)
+ manager.save_state.assert_not_called()
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
+ def test_status_mapping(self, _label: str, status_code: int, expected: bool, mock_session: MagicMock) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("key") is expected
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
+ def test_transient_errors_raise(self, _label: str, status_code: int, mock_session: MagicMock) -> None:
+ # Transient/unexpected statuses must not be reported as an invalid API key — they raise.
+ response = MagicMock()
+ response.status_code = status_code
+ response.raise_for_status.side_effect = HTTPError
+ mock_session.return_value.get.return_value = response
+
+ with pytest.raises(HTTPError):
+ validate_credentials("key")
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
+ def test_sends_raw_key_in_authorization_header(self, mock_session: MagicMock) -> None:
+ # Appstack expects the bare key — a Bearer prefix breaks auth for every sync.
+ response = MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("the-key")
+
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "the-key"
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
+ def test_probe_disables_sample_capture(self, mock_session: MagicMock) -> None:
+ # The probe hits the same export endpoint, so its response body must not be captured either.
+ response = MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("the-key")
+
+ assert mock_session.call_args.kwargs["capture"] is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack_source.py
new file mode 100644
index 000000000000..ed63d307ed88
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack_source.py
@@ -0,0 +1,148 @@
+from typing import Any, cast
+
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack import AppstackResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.settings import (
+ DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.source import AppstackSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appstack import (
+ AppstackSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> AppstackSourceConfig:
+ return AppstackSourceConfig(api_key="appstack-key")
+
+
+class TestAppstackSourceConfig:
+ def test_source_type(self) -> None:
+ assert AppstackSource().source_type == ExternalDataSourceType.APPSTACK
+
+ def test_get_source_config(self) -> None:
+ config = AppstackSource().get_source_config
+ assert config.name == SchemaExternalDataSourceType.APPSTACK
+ assert config.category == DataWarehouseSourceCategory.ADVERTISING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # The source ships visible: the scaffold's unreleasedSource flag must stay deleted.
+ assert not config.unreleasedSource
+
+ def test_single_secret_api_key_field(self) -> None:
+ fields = AppstackSource().get_source_config.fields
+ assert fields is not None
+ assert len(fields) == 1
+ api_key_field = fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+
+class TestGetSchemas:
+ def test_events_schema(self) -> None:
+ schemas = AppstackSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ events = next(s for s in schemas if s.name == "events")
+ assert events.supports_incremental is True
+ # The lookback re-reads a trailing window each run; append would duplicate the overlap.
+ assert events.supports_append is False
+ assert [f["field"] for f in events.incremental_fields] == ["event_time"]
+ assert events.default_incremental_lookback_seconds == DEFAULT_INCREMENTAL_LOOKBACK_SECONDS
+
+ def test_names_filter(self) -> None:
+ assert AppstackSource().get_schemas(_config(), team_id=1, names=["nonexistent"]) == []
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.appstack.source.validate_appstack_credentials"
+ )
+ def test_validate(self, _label: str, api_result: bool, expected_ok: bool, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = api_result
+ ok, error = AppstackSource().validate_credentials(_config(), team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.appstack.source.validate_appstack_credentials"
+ )
+ def test_network_blip_is_not_reported_as_bad_credentials(self, mock_validate: MagicMock) -> None:
+ mock_validate.side_effect = requests.ConnectionError("boom")
+ ok, error = AppstackSource().validate_credentials(_config(), team_id=1)
+ assert ok is False
+ assert error is not None
+ assert "try again" in error
+
+
+class TestSourceWiring:
+ def test_non_retryable_errors_cover_auth(self) -> None:
+ errors = AppstackSource().get_non_retryable_errors()
+ keys = " ".join(errors.keys())
+ assert "401" in keys
+ assert "403" in keys
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = AppstackSource().get_resumable_source_manager(MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AppstackResumeConfig
+
+ def test_canonical_descriptions_match_endpoints(self) -> None:
+ descriptions = AppstackSource().get_canonical_descriptions()
+ assert "events" in descriptions
+ assert set(descriptions.keys()).issubset(set(ENDPOINTS))
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # `lists_tables_without_credentials` powers the public docs' Supported tables section.
+ tables = AppstackSource().get_documented_tables()
+ assert [t["name"] for t in tables] == ["events"]
+ assert tables[0]["description"]
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.source.appstack_source")
+ def test_source_for_pipeline_plumbing(self, mock_appstack_source: MagicMock) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = MagicMock()
+ inputs.schema_name = "events"
+ inputs.team_id = 7
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"
+
+ AppstackSource().source_for_pipeline(_config(), manager, inputs)
+
+ kwargs = cast(dict[str, Any], mock_appstack_source.call_args.kwargs)
+ assert kwargs["api_key"] == "appstack-key"
+ assert kwargs["endpoint"] == "events"
+ assert kwargs["team_id"] == 7
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"
+ assert kwargs["resumable_source_manager"] is manager
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.source.appstack_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_appstack_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "events"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+
+ AppstackSource().source_for_pipeline(_config(), MagicMock(spec=ResumableSourceManager), inputs)
+
+ assert mock_appstack_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstack.py
index a1df230891d8..755beb784621 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstack.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AppstackSourceConfig(config.Config):
- pass
+ api_key: str