: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 autumn import source (#72644)
Tom Owers6ddc2afd2267
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a1935938edec..03351f006e38 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -73,6 +73,7 @@ the row lists both.| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ || automox | HTTP | requests | ✅ |+| autumn | HTTP | requests + `rest_source.RESTClient` | ✅ || aviationstack | HTTP | requests | ✅ || aviator | HTTP | requests | ✅ || awin | HTTP | requests | ✅ |@@ -644,7 +645,6 @@ doesn't conflict with concurrent PRs.- asknicely- auth0- automox-- autumn- aws_cloudtrail- axiom- azure_blobdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/autumn.py b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/autumn.pynew file mode 100644index 000000000000..aca2bbd720c8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/autumn.py@@ -0,0 +1,203 @@+import dataclasses+from datetime import UTC, datetime+from typing import Any, Optional++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ PartitionMode,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.settings import (+ AUTUMN_BASE_URL,+ AUTUMN_ENDPOINTS,+ PARTITION_BUCKET_MILLISECONDS,+ AutumnEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++class AutumnResumeConfig:+ next_cursor: str+++def _watermark_to_epoch_ms(value: Any) -> int:+ """Coerce the persisted incremental watermark to epoch milliseconds."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return int(dt.timestamp() * 1000)+ return int(value)+++def _make_paginator(config: AutumnEndpointConfig) -> BasePaginator:+ if config.paginated:+ return JSONResponseCursorPaginator(+ cursor_path="next_cursor",+ cursor_param="start_cursor",+ param_location="json",+ )+ return SinglePagePaginator()+++def _build_request_body(+ config: AutumnEndpointConfig,+ should_use_incremental_field: bool,+ incremental_field: Optional[str],+ db_incremental_field_last_value: Optional[Any],+) -> dict[str, Any]:+ # Single-page endpoints document an optional (or absent) request body; an empty JSON+ # object is accepted either way and keeps the request shape uniform.+ body: dict[str, Any] = {}+ if config.paginated:+ body["limit"] = config.page_size+ if (+ config.incremental_range_field is not None+ and should_use_incremental_field+ and incremental_field == config.incremental_range_field+ and db_incremental_field_last_value is not None+ ):+ # The docs don't state whether custom_range.start is inclusive; starting exactly at+ # the watermark may re-fetch boundary rows, which the merge on primary key dedupes.+ body["custom_range"] = {"start": _watermark_to_epoch_ms(db_incremental_field_last_value)}+ return body+++def get_resource(+ endpoint: str,+ should_use_incremental_field: bool,+ json_body: dict[str, Any],+) -> EndpointResource:+ config = AUTUMN_ENDPOINTS[endpoint]++ endpoint_config: Endpoint = {+ "method": "POST",+ "path": config.path,+ "json": json_body,+ "data_selector": config.data_selector,+ "paginator": _make_paginator(config),+ }++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def autumn_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[AutumnResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceResponse:+ config = AUTUMN_ENDPOINTS[endpoint]++ json_body = _build_request_body(+ config,+ should_use_incremental_field,+ incremental_field,+ db_incremental_field_last_value,+ )++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": AUTUMN_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "headers": {"x-api-version": api_version},+ },+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field, json_body)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if config.paginated and resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.next_cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles+ # cleanup on completion.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(AutumnResumeConfig(next_cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ # Incremental filtering rides the custom_range body param above, not the+ # framework's query-param incremental machinery.+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ partition_keys: Optional[list[str]] = None+ partition_mode: Optional[PartitionMode] = None+ partition_size: Optional[int] = None+ if config.partition_key is not None:+ partition_keys = [config.partition_key]+ partition_mode = "numerical"+ partition_size = PARTITION_BUCKET_MILLISECONDS++ return SourceResponse(+ name=config.name,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_keys=partition_keys,+ partition_mode=partition_mode,+ partition_size=partition_size,+ # The docs don't state list ordering; usage-event logs are typically newest-first,+ # and "desc" is also the safe choice if the order turns out to be ascending — the+ # watermark then only commits once the sync completes.+ sort_mode="desc" if config.incremental_range_field is not None else "asc",+ )+++def validate_credentials(api_key: str, api_version: str) -> tuple[bool, str | None]:+ session = make_tracked_session(redact_values=(api_key,))+ response = session.post(+ f"{AUTUMN_BASE_URL}/v1/customers.list",+ headers={+ "Authorization": f"Bearer {api_key}",+ "x-api-version": api_version,+ },+ json={"limit": 1},+ timeout=30,+ )+ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, (+ "Autumn rejected the secret key. Check that you copied a secret key (am_sk_...) "+ "for the environment you want to sync."+ )+ return False, f"Autumn returned an unexpected status ({response.status_code})"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/canonical_descriptions.pynew file mode 100644index 000000000000..a7e44af9f71b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/canonical_descriptions.py@@ -0,0 +1,121 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Customers": {+ "description": "A customer with their subscriptions, purchases, balances, and billing controls.",+ "docs_url": "https://docs.useautumn.com/api-reference/customers/listCustomers",+ "columns": {+ "id": "Your unique identifier for the customer.",+ "name": "The name of the customer.",+ "email": "The email address of the customer.",+ "created_at": "Time the customer was created, as a Unix timestamp in milliseconds.",+ "fingerprint": "Unique identifier (e.g. serial number) used to detect duplicate customers and prevent free trial abuse.",+ "stripe_id": "The Stripe customer ID linked to this customer.",+ "env": "Environment the customer belongs to: sandbox or live.",+ "metadata": "Arbitrary key-value metadata attached to the customer.",+ "subscriptions": "The customer's subscriptions, each with its plan, status, and billing period.",+ "purchases": "One-off (non-recurring) plan purchases made by the customer.",+ "balances": "The customer's feature balances, including usage and remaining allowances.",+ "billing_controls": "Overage behavior, spend limits, usage alerts, and auto top-up configuration for the customer.",+ },+ },+ "Events": {+ "description": "A usage event recorded for a customer feature, with the balance deductions it caused.",+ "docs_url": "https://docs.useautumn.com/api-reference/events/listEvents",+ "columns": {+ "id": "Unique identifier for the event.",+ "timestamp": "Time the event was recorded, as a Unix timestamp in milliseconds.",+ "feature_id": "ID of the feature this event tracked usage for.",+ "customer_id": "ID of the customer the event belongs to.",+ "value": "Usage amount recorded by the event.",+ "properties": "Arbitrary properties attached to the event.",+ "deductions": "Balance deductions applied by this event, per feature balance.",+ },+ },+ "Features": {+ "description": "A feature configured for the organization: boolean access, metered usage, or a credit system.",+ "docs_url": "https://docs.useautumn.com/api-reference/features/listFeatures",+ "columns": {+ "id": "The unique identifier for this feature, used in check and track calls.",+ "name": "Human-readable name displayed in the dashboard and billing UI.",+ "type": "Feature type: boolean for on/off access, metered for usage-tracked features, credit_system for unified credit pools, ai_credit_system for model-based token pricing.",+ "consumable": "For metered features: true if usage resets periodically, false if allocated persistently (seats, storage).",+ "event_names": "Event names that trigger this feature's balance. Allows multiple features to respond to a single event.",+ "credit_schema": "For credit systems: the metered features that draw from this credit pool and their costs.",+ },+ },+ "Plans": {+ "description": "A pricing plan with its base price and feature configurations.",+ "docs_url": "https://docs.useautumn.com/api-reference/plans/listPlans",+ "columns": {+ "id": "Unique identifier for the plan.",+ "name": "Display name of the plan.",+ "description": "Optional description of the plan.",+ "group": "Group identifier for organizing related plans.",+ "version": "Version number of the plan; updating a plan creates a new version.",+ "add_on": "Whether the plan is an add-on that can be attached alongside a main plan.",+ "auto_enable": "Whether the plan is automatically enabled for new customers.",+ "price": "Base price of the plan, with amount, currency options, and billing interval.",+ "items": "The plan's items: features included, allowances, and usage prices.",+ },+ },+ "Entities": {+ "description": "A feature entity (e.g. a seat or workspace) tracking balances separately under a parent customer.",+ "docs_url": "https://docs.useautumn.com/api-reference/entities/listEntities",+ "columns": {+ "id": "Your unique identifier for the entity, unique within its parent customer.",+ "name": "The name of the entity.",+ "customer_id": "ID of the parent customer the entity belongs to.",+ "feature_id": "ID of the feature this entity was created for.",+ "created_at": "Time the entity was created, as a Unix timestamp in milliseconds.",+ "env": "Environment the entity belongs to: sandbox or live.",+ "subscriptions": "Subscriptions attached to the entity, including plans inherited from the parent customer.",+ },+ },+ "Invoices": {+ "description": "An invoice issued to a customer through the connected billing processor.",+ "docs_url": "https://docs.useautumn.com/api-reference/invoices/listInvoices",+ "columns": {+ "id": "Unique identifier for the invoice.",+ "customer_id": "ID of the customer the invoice belongs to.",+ "entity_id": "ID of the entity the invoice belongs to, if entity-scoped.",+ "plan_ids": "IDs of the plans billed on this invoice.",+ "stripe_id": "The Stripe invoice ID.",+ "processor_type": "Billing processor that issued the invoice: stripe or revenuecat.",+ "status": "Invoice status: draft, open, paid, void, or uncollectible.",+ "total": "Total amount of the invoice.",+ "amount_paid": "Amount paid on the invoice so far.",+ "refunded_amount": "Amount refunded on the invoice.",+ "currency": "Three-letter currency code of the invoice.",+ "created_at": "Time the invoice was created, as a Unix timestamp in milliseconds.",+ "hosted_invoice_url": "URL of the hosted invoice page, when available.",+ },+ },+ "Coupons": {+ "description": "A coupon (discount reward) configured for the organization, with its promo codes.",+ "docs_url": "https://docs.useautumn.com/api-reference/rewards/listRewards",+ "columns": {+ "id": "The unique identifier for the coupon.",+ "name": "A human-readable name for the coupon.",+ "type": "The type of discount: percentage_discount, fixed_discount, or invoice_credits.",+ "value": "The discount value: a percentage for percentage_discount, or an amount for fixed_discount and invoice_credits.",+ "duration": "How long the discount lasts: one_off, a number of months, or forever.",+ "plan_ids": "Plans the coupon is restricted to, if any.",+ "promo_codes": "Redeemable promo codes for this coupon, with redemption limits.",+ "created_at": "Time the coupon was created, as a Unix timestamp in milliseconds.",+ },+ },+ "FeatureGrants": {+ "description": "A feature-grant reward that gives customers extra feature allowance when redeemed.",+ "docs_url": "https://docs.useautumn.com/api-reference/rewards/listRewards",+ "columns": {+ "id": "The unique identifier for the feature grant.",+ "name": "A human-readable name for the feature grant.",+ "grants": "Features granted on redemption, with included amounts and optional expiry.",+ "promo_codes": "Redeemable promo codes for this grant, with usage limits.",+ "created_at": "Time the feature grant was created, as a Unix timestamp in milliseconds.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/settings.pynew file mode 100644index 000000000000..da3ed415e724--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/settings.py@@ -0,0 +1,101 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++AUTUMN_BASE_URL = "https://api.useautumn.com"++# Autumn timestamps are epoch milliseconds, so "datetime" partition mode (which expects epoch+# seconds for integer values) can't be used. Numerical bucketing on the raw value with a+# one-week bucket size yields the same stable weekly partitions.+PARTITION_BUCKET_MILLISECONDS = 7 * 24 * 60 * 60 * 1000+++@dataclass+class AutumnEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ data_selector: str = "list"+ # Cursor-paginated endpoints take start_cursor/limit in the POST body and return+ # next_cursor (null when exhausted); the rest return everything in one page.+ paginated: bool = True+ page_size: int = 500+ partition_key: str | None = None+ # Field the server-side custom_range filter applies to (epoch milliseconds). Only+ # events.list supports a time-range filter; every other list endpoint is full refresh.+ incremental_range_field: str | None = None+++AUTUMN_ENDPOINTS: dict[str, AutumnEndpointConfig] = {+ "Customers": AutumnEndpointConfig(+ name="Customers",+ path="/v1/customers.list",+ primary_keys=["id"],+ # Customer objects are wide (subscriptions, purchases, billing controls), so keep+ # pages small; customers.list is also rate-limited to 5 req/s per org.+ page_size=100,+ partition_key="created_at",+ ),+ "Events": AutumnEndpointConfig(+ name="Events",+ path="/v1/events.list",+ primary_keys=["id"],+ page_size=1000,+ partition_key="timestamp",+ incremental_range_field="timestamp",+ ),+ "Features": AutumnEndpointConfig(+ name="Features",+ path="/v1/features.list",+ primary_keys=["id"],+ paginated=False,+ ),+ "Plans": AutumnEndpointConfig(+ name="Plans",+ path="/v1/plans.list",+ primary_keys=["id"],+ paginated=False,+ ),+ "Entities": AutumnEndpointConfig(+ name="Entities",+ path="/v1/entities.list",+ # Entity ids are only unique within their parent customer.+ primary_keys=["customer_id", "id"],+ page_size=100,+ partition_key="created_at",+ ),+ "Invoices": AutumnEndpointConfig(+ name="Invoices",+ path="/v1/invoices.list",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ # rewards.list returns two root arrays; each becomes its own table via data_selector.+ "Coupons": AutumnEndpointConfig(+ name="Coupons",+ path="/v1/rewards.list",+ primary_keys=["id"],+ data_selector="coupons",+ paginated=False,+ ),+ "FeatureGrants": AutumnEndpointConfig(+ name="FeatureGrants",+ path="/v1/rewards.list",+ primary_keys=["id"],+ data_selector="feature_grants",+ paginated=False,+ ),+}++ENDPOINTS = tuple(AUTUMN_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "Events": [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.Integer,+ "field": "timestamp",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/source.pyindex 8a90d044ba03..ee937677b185 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/source.py@@ -1,31 +1,135 @@-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.autumn.autumn import (+ AutumnResumeConfig,+ autumn_source,+ validate_credentials as validate_autumn_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.settings import (+ 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.autumn import AutumnSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AutumnSource(SimpleSource[AutumnSourceConfig]):+class AutumnSource(ResumableSource[AutumnSourceConfig, AutumnResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("2.3.0",)+ default_version = "2.3.0"+ api_docs_url = "https://docs.useautumn.com/api-reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AUTUMN+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.useautumn.com": (+ "Your Autumn secret key is invalid or was revoked. Generate a new secret key in the "+ "Autumn dashboard and update the source."+ ),+ "403 Client Error: Forbidden for url: https://api.useautumn.com": (+ "Your Autumn secret key does not have access to this data. Check the key's environment "+ "in the Autumn dashboard."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AutumnSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: AutumnSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_autumn_credentials(config.api_key, self.default_version)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AutumnResumeConfig]:+ return ResumableSourceManager[AutumnResumeConfig](inputs, AutumnResumeConfig)++ def source_for_pipeline(+ self,+ config: AutumnSourceConfig,+ resumable_source_manager: ResumableSourceManager[AutumnResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return autumn_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AUTUMN,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Autumn",+ caption=(+ "Sync customers, usage events, features, plans, entities, invoices, and rewards from Autumn. "+ "Create a secret key (`am_sk_...`) in the Autumn dashboard under Developer settings. "+ "Sandbox and production have separate keys, so use the key for the environment you want to sync."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/autumn",iconPath="/static/services/autumn.png",keywords=["billing", "subscriptions", "useautumn"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Secret API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="am_sk_...",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn.py b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn.pynew file mode 100644index 000000000000..08f1f21c5797--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn.py@@ -0,0 +1,298 @@+import json+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, Optional, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.autumn import (+ AutumnResumeConfig,+ _build_request_body,+ autumn_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.settings import (+ AUTUMN_ENDPOINTS,+ PARTITION_BUCKET_MILLISECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++WATERMARK_MS = 1704067200000+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestBuildRequestBody:+ @pytest.mark.parametrize(+ ("endpoint", "should_use_incremental_field", "incremental_field", "last_value", "expected"),+ [+ ("Customers", False, None, None, {"limit": 100}),+ ("Events", False, None, None, {"limit": 1000}),+ # First incremental sync has no watermark yet — no custom_range.+ ("Events", True, "timestamp", None, {"limit": 1000}),+ (+ "Events",+ True,+ "timestamp",+ WATERMARK_MS,+ {"limit": 1000, "custom_range": {"start": WATERMARK_MS}},+ ),+ # The user's chosen incremental field is honored — an unknown field is not+ # silently mapped onto the timestamp filter.+ ("Events", True, "created_at", WATERMARK_MS, {"limit": 1000}),+ # Only events.list supports the server-side time filter.+ ("Customers", True, "created_at", WATERMARK_MS, {"limit": 100}),+ ("Coupons", False, None, None, {}),+ ],+ )+ def test_body_shape(+ self,+ endpoint: str,+ should_use_incremental_field: bool,+ incremental_field: Optional[str],+ last_value: Optional[Any],+ expected: dict[str, Any],+ ) -> None:+ body = _build_request_body(+ AUTUMN_ENDPOINTS[endpoint],+ should_use_incremental_field,+ incremental_field,+ last_value,+ )+ assert body == expected++ def test_datetime_watermark_is_coerced_to_epoch_ms(self) -> None:+ body = _build_request_body(+ AUTUMN_ENDPOINTS["Events"],+ True,+ "timestamp",+ datetime(2024, 1, 1, tzinfo=UTC),+ )+ assert body["custom_range"] == {"start": WATERMARK_MS}+++class TestAutumnSourceBehavior:+ """End-to-end behavior of ``autumn_source`` via ``rest_api_resource`` with a mocked session."""++ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+ ) -> tuple[MagicMock, list[dict[str, Any]], list[dict[str, Any]]]:+ """Returns ``(mock_session, sent_bodies, rows)``. ``sent_bodies`` are shallow copies of+ ``request.json`` captured at send-time — the Request object is mutated in place by the+ paginator between pages."""+ sent_bodies: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_bodies.append(dict(request.json or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = autumn_source(+ api_key="am_sk_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ api_version="2.3.0",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ )+ rows = [row for page in cast(Iterable[Any], source_response.items()) for row in page]+ return mock_session, sent_bodies, rows++ def test_fresh_run_pages_with_body_cursor_and_saves_state_after_each_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"list": [{"id": "cus_1"}], "next_cursor": "cursor-1"}),+ _make_http_response({"list": [{"id": "cus_2"}], "next_cursor": "cursor-2"}),+ _make_http_response({"list": [{"id": "cus_3"}], "next_cursor": None}),+ ]+ _, sent_bodies, rows = self._drive("Customers", manager, responses)++ assert [body.get("start_cursor") for body in sent_bodies] == [None, "cursor-1", "cursor-2"]+ assert all(body["limit"] == 100 for body in sent_bodies)+ assert [row["id"] for row in rows] == ["cus_1", "cus_2", "cus_3"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ AutumnResumeConfig(next_cursor="cursor-1"),+ AutumnResumeConfig(next_cursor="cursor-2"),+ ]++ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = AutumnResumeConfig(next_cursor="cursor-resumed")++ responses = [+ _make_http_response({"list": [{"id": "cus_4"}], "next_cursor": None}),+ ]+ _, sent_bodies, _ = self._drive("Customers", manager, responses)++ assert [body.get("start_cursor") for body in sent_bodies] == ["cursor-resumed"]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"list": [{"id": "only"}], "next_cursor": None}),+ ]+ self._drive("Customers", manager, responses)++ manager.save_state.assert_not_called()++ def test_incremental_events_run_carries_custom_range_on_every_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"list": [{"id": "evt_1", "timestamp": 1}], "next_cursor": "cursor-1"}),+ _make_http_response({"list": [{"id": "evt_2", "timestamp": 2}], "next_cursor": None}),+ ]+ _, sent_bodies, _ = self._drive(+ "Events",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=WATERMARK_MS,+ incremental_field="timestamp",+ )++ assert all(body["custom_range"] == {"start": WATERMARK_MS} for body in sent_bodies)++ @pytest.mark.parametrize(+ ("endpoint", "selector", "row_id"),+ [+ ("Coupons", "coupons", "coupon_1"),+ ("FeatureGrants", "feature_grants", "grant_1"),+ ],+ )+ def test_single_page_endpoints_issue_one_request_and_select_their_root_array(+ self, endpoint: str, selector: str, row_id: str+ ) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"coupons": [{"id": "coupon_1"}], "feature_grants": [{"id": "grant_1"}]}),+ ]+ _, sent_bodies, rows = self._drive(endpoint, manager, responses)++ assert len(sent_bodies) == 1+ assert [row["id"] for row in rows] == [row_id]+ manager.save_state.assert_not_called()+ manager.load_state.assert_not_called()++ def test_required_api_version_header_is_set_on_the_session(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"list": [], "next_cursor": None}),+ ]+ mock_session, _, _ = self._drive("Customers", manager, responses)++ assert mock_session.headers.get("x-api-version") == "2.3.0"++ @pytest.mark.parametrize(+ ("endpoint", "expected_primary_keys", "expected_sort_mode"),+ [+ ("Customers", ["id"], "asc"),+ ("Events", ["id"], "desc"),+ # Entity ids are only unique within their parent customer.+ ("Entities", ["customer_id", "id"], "asc"),+ ],+ )+ def test_source_response_keys_and_sort_mode(+ self, endpoint: str, expected_primary_keys: list[str], expected_sort_mode: str+ ) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch("products.warehouse_sources.backend.temporal.data_imports.sources.autumn.autumn.rest_api_resource"):+ source_response = autumn_source(+ api_key="am_sk_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ api_version="2.3.0",+ resumable_source_manager=manager,+ )++ assert source_response.primary_keys == expected_primary_keys+ assert source_response.sort_mode == expected_sort_mode++ def test_events_partitioning_uses_numerical_buckets_for_epoch_ms(self) -> None:+ # "datetime" partition mode interprets integer values as epoch seconds; Autumn returns+ # epoch milliseconds, which would crash the partitioner.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch("products.warehouse_sources.backend.temporal.data_imports.sources.autumn.autumn.rest_api_resource"):+ source_response = autumn_source(+ api_key="am_sk_test",+ endpoint="Events",+ team_id=123,+ job_id="test_job",+ api_version="2.3.0",+ resumable_source_manager=manager,+ )++ assert source_response.partition_mode == "numerical"+ assert source_response.partition_keys == ["timestamp"]+ assert source_response.partition_size == PARTITION_BUCKET_MILLISECONDS+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.autumn.autumn.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.post.return_value = _make_http_response({}, status_code=status_code)++ valid, error = validate_credentials("am_sk_test", "2.3.0")++ assert valid is expected_valid+ assert (error is None) is expected_valid++ _, kwargs = mock_session.post.call_args+ assert kwargs["headers"]["Authorization"] == "Bearer am_sk_test"+ assert kwargs["headers"]["x-api-version"] == "2.3.0"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn_source.pynew file mode 100644index 000000000000..2c4c056853bf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn_source.py@@ -0,0 +1,122 @@+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.autumn import AutumnResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.autumn.source import AutumnSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.autumn import AutumnSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(+ schema_name: str = "Customers",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+ api_version: Optional[str] = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field=incremental_field,+ incremental_field_type=None,+ job_id="job-id",+ logger=MagicMock(),+ reset_pipeline=False,+ api_version=api_version,+ )+++class TestAutumnSource:+ def setup_method(self) -> None:+ self.source = AutumnSource()+ self.config = AutumnSourceConfig(api_key="am_sk_test")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.AUTUMN++ def test_get_schemas_advertises_incremental_only_for_events(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=123)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)++ by_name = {schema.name: schema for schema in schemas}+ incremental_names = [name for name, schema in by_name.items() if schema.supports_incremental]+ assert incremental_names == ["Events"]+ assert [field["field"] for field in by_name["Events"].incremental_fields] == ["timestamp"]++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=123, names=["Events", "Invoices"])++ assert {schema.name for schema in schemas} == {"Events", "Invoices"}++ def test_validate_credentials_delegates_with_pinned_api_version(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.autumn.source.validate_autumn_credentials",+ return_value=(True, None),+ ) as mock_validate:+ assert self.source.validate_credentials(self.config, team_id=123) == (True, None)++ mock_validate.assert_called_once_with("am_sk_test", "2.3.0")++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())++ assert manager._data_class is AutumnResumeConfig++ @pytest.mark.parametrize(+ ("should_use_incremental_field", "expected_last_value"),+ [+ (True, 1704067200000),+ # A stale watermark must not leak into a full-refresh run.+ (False, None),+ ],+ )+ def test_source_for_pipeline_plumbing(+ self, should_use_incremental_field: bool, expected_last_value: Optional[int]+ ) -> None:+ inputs = _make_inputs(+ schema_name="Events",+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=1704067200000,+ incremental_field="timestamp",+ )+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.autumn.source.autumn_source"+ ) as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="am_sk_test",+ endpoint="Events",+ team_id=123,+ job_id="job-id",+ api_version="2.3.0",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=expected_last_value,+ incremental_field="timestamp",+ )++ def test_source_config_keeps_api_key_secret_and_source_visible(self) -> None:+ config = self.source.get_source_config++ assert config.unreleasedSource is not True++ (api_key_field,) = config.fields+ 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 Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/autumn.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/autumn.pyindex f158e09b4ff1..9ae69b65dfc4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/autumn.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/autumn.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AutumnSourceConfig(config.Config):- pass+ api_key: str