: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 aha import source (#66731)
Tom Owersd7905adb987f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1752b33c6f7f..6cd48d07920d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -46,6 +46,7 @@ the row lists both.| ----------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || adroll | HTTP | requests | ✅ || agilecrm | HTTP | requests | ✅ |+| aha | HTTP | requests | ✅ || aircall | HTTP | requests | ✅ || airtable | HTTP | requests | ✅ || algolia | HTTP | requests | ✅ |@@ -299,7 +300,6 @@ doesn't conflict with concurrent PRs.- adobe_commerce- adp_workforce_now- adyen-- aha- ahrefs- airbyte- akeneodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/aha.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/aha.pynew file mode 100644index 000000000000..e126ed7a0096--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/aha.py@@ -0,0 +1,218 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import (+ AHA_ENDPOINTS,+ PER_PAGE,+ AhaEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++AHA_API_PATH = "/api/v1"++# A single DNS label: letters, digits, hyphens. Rejects anything that could retarget the host+# (slashes, `@`, dots) so the stored API key is only ever sent to `<subdomain>.aha.io`.+_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")+++class AhaRetryableError(Exception):+ pass+++class AhaResumeConfig:+ # Next 1-indexed page to fetch. None means "start from page 1".+ next_page: int | None = None+++def normalize_subdomain(subdomain: str) -> str:+ """Reduce user input to a bare, validated Aha! subdomain label.++ Accepts either the full host (``yourcompany.aha.io``) or the bare subdomain+ (``yourcompany``). Raises ``ValueError`` on anything that isn't a single DNS label so the+ API key can never be retargeted away from ``<subdomain>.aha.io``.+ """+ cleaned = subdomain.strip().removeprefix("https://").removeprefix("http://")+ cleaned = cleaned.strip("/")+ cleaned = cleaned.removesuffix(".aha.io")+ if not _SUBDOMAIN_RE.match(cleaned):+ raise ValueError(+ f"Invalid Aha! account domain: {subdomain!r}. Enter just your subdomain, e.g. 'yourcompany' "+ "for yourcompany.aha.io."+ )+ return cleaned+++def _base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.aha.io{AHA_API_PATH}"+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def _format_updated_since(value: Any) -> str:+ """Format an incremental cursor as the ISO8601 UTC string Aha! expects for `updated_since`."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params)}"+++def _build_initial_params(+ config: AhaEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"per_page": PER_PAGE}+ # Only Aha!'s `updated_since`-capable endpoints filter server-side; everything else is full refresh.+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:+ params["updated_since"] = _format_updated_since(db_incremental_field_last_value)+ return params+++@retry(+ retry=retry_if_exception_type((AhaRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ response = session.get(url, headers=headers, timeout=60)++ # Aha! enforces 300 req/min and 20 req/sec; 429 carries reset headers. Back off and retry rather+ # than failing the sync. Transient 5xx are retryable too.+ if response.status_code == 429 or response.status_code >= 500:+ raise AhaRetryableError(f"Aha! API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Aha! API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _has_more_pages(pagination: dict[str, Any], page: int, item_count: int) -> bool:+ """Decide whether to fetch another page.++ Prefer Aha!'s `pagination.total_pages`; fall back to a full-page heuristic if the metadata is+ ever absent (a full page implies there may be more).+ """+ total_pages = pagination.get("total_pages")+ if isinstance(total_pages, int):+ return page < total_pages+ return item_count >= PER_PAGE+++def get_rows(+ subdomain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AhaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = AHA_ENDPOINTS[endpoint]+ base_url = _base_url(subdomain)+ headers = _headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ session = make_tracked_session()++ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume is not None and resume.next_page else 1+ if page > 1:+ logger.debug(f"Aha!: resuming {endpoint} from page {page}")++ while True:+ data = _fetch_page(session, _build_url(base_url, config.path, {**params, "page": page}), headers, logger)+ items = data.get(config.response_key, [])+ if not items:+ break++ has_more = _has_more_pages(data.get("pagination", {}), page, len(items))++ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ if has_more:+ resumable_source_manager.save_state(AhaResumeConfig(next_page=page + 1))++ if not has_more:+ break+ page += 1++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def aha_source(+ subdomain: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AhaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = AHA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ subdomain=subdomain,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(subdomain: str, api_key: str) -> tuple[bool, int | None]:+ """Probe Aha!'s `/me` endpoint to confirm the token is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises+ ``ValueError`` if the subdomain is malformed so the caller can surface a precise message.+ """+ url = _build_url(_base_url(subdomain), "/me", {})+ try:+ response = make_tracked_session().get(url, headers=_headers(api_key), timeout=10)+ except Exception:+ return False, None+ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/canonical_descriptions.pynew file mode 100644index 000000000000..4b4f395755f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/canonical_descriptions.py@@ -0,0 +1,125 @@+"""Canonical, documentation-sourced descriptions for Aha! endpoints and columns.++Sourced from the official Aha! API reference (https://www.aha.io/api). Keyed by the endpoint names+in `settings.py` `AHA_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced Aha! table.+Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Fields common to most Aha! record types.+_COMMON_COLUMNS = {+ "id": "Unique identifier for the record.",+ "reference_num": "Human-readable reference number (e.g. PRJ1-123).",+ "name": "The record's name.",+ "created_at": "Time at which the record was created.",+ "updated_at": "Time at which the record was last updated.",+ "url": "URL of the record in the Aha! web app.",+ "resource": "API URL of the record.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "products": {+ "description": "A product (workspace) in your Aha! account that groups releases, features, and ideas.",+ "docs_url": "https://www.aha.io/api/resources/products",+ "columns": {+ "id": "Unique identifier for the product.",+ "reference_prefix": "Prefix used for reference numbers of records in this product.",+ "name": "The product's name.",+ "product_line": "Whether the product is a product line (container) rather than a leaf product.",+ "created_at": "Time at which the product was created.",+ "updated_at": "Time at which the product was last updated.",+ },+ },+ "features": {+ "description": "A feature in Aha! — a unit of work delivered as part of a release.",+ "docs_url": "https://www.aha.io/api/resources/features",+ "columns": {+ **_COMMON_COLUMNS,+ "workflow_status": "The feature's current status in its workflow.",+ "release_id": "Identifier of the release this feature belongs to.",+ "initiative": "The initiative this feature is associated with.",+ "epic": "The epic this feature is associated with.",+ "score": "The feature's score from the configured scorecard.",+ "progress": "Completion progress of the feature, as a percentage.",+ "start_date": "Planned start date for the feature.",+ "due_date": "Planned due date for the feature.",+ "assigned_to_user": "The user the feature is assigned to.",+ },+ },+ "epics": {+ "description": "An epic in Aha! — a large body of work that groups related features.",+ "docs_url": "https://www.aha.io/api/resources/epics",+ "columns": {+ **_COMMON_COLUMNS,+ "workflow_status": "The epic's current status in its workflow.",+ "release_id": "Identifier of the release this epic belongs to.",+ "initiative": "The initiative this epic is associated with.",+ "progress": "Completion progress of the epic, as a percentage.",+ },+ },+ "initiatives": {+ "description": "An initiative in Aha! — a strategic effort that groups goals, epics, and features.",+ "docs_url": "https://www.aha.io/api/resources/initiatives",+ "columns": {+ **_COMMON_COLUMNS,+ "workflow_status": "The initiative's current status in its workflow.",+ "effort": "Estimated effort for the initiative.",+ "value": "Estimated value of the initiative.",+ "start_date": "Planned start date for the initiative.",+ "end_date": "Planned end date for the initiative.",+ },+ },+ "ideas": {+ "description": "An idea submitted in Aha! Ideas — feedback that can be promoted into features.",+ "docs_url": "https://www.aha.io/api/resources/ideas",+ "columns": {+ **_COMMON_COLUMNS,+ "workflow_status": "The idea's current status in its workflow.",+ "score": "The idea's score.",+ "votes": "Number of votes the idea has received.",+ "endorsements_count": "Number of endorsements the idea has received.",+ "product_id": "Identifier of the product the idea belongs to.",+ "created_by_idea_user": "The user who submitted the idea.",+ },+ },+ "goals": {+ "description": "A goal in Aha! — a measurable objective that initiatives and releases roll up to.",+ "docs_url": "https://www.aha.io/api/resources/goals",+ "columns": {+ **_COMMON_COLUMNS,+ "description": "Description of the goal.",+ "effort": "Estimated effort for the goal.",+ "value": "Estimated value of the goal.",+ "start_date": "Planned start date for the goal.",+ "end_date": "Planned end date for the goal.",+ },+ },+ "todos": {+ "description": "A to-do (task) in Aha! assigned to a user against a record.",+ "docs_url": "https://www.aha.io/api/resources/to-dos",+ "columns": {+ "id": "Unique identifier for the to-do.",+ "name": "The to-do's name.",+ "body": "The to-do's description.",+ "status": "Current status of the to-do (e.g. pending, complete).",+ "due_date": "Date the to-do is due.",+ "assigned_to_user": "The user the to-do is assigned to.",+ "created_at": "Time at which the to-do was created.",+ "updated_at": "Time at which the to-do was last updated.",+ },+ },+ "users": {+ "description": "A user in your Aha! account.",+ "docs_url": "https://www.aha.io/api/resources/users",+ "columns": {+ "id": "Unique identifier for the user.",+ "name": "The user's full name.",+ "email": "The user's email address.",+ "created_at": "Time at which the user was created.",+ "updated_at": "Time at which the user was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/settings.pynew file mode 100644index 000000000000..c4caff49fdb4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/settings.py@@ -0,0 +1,102 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Aha! caps `per_page` at 200 (default 30). Always request the max to minimise round trips.+PER_PAGE = 200+++def _updated_at_incremental_fields() -> list[IncrementalField]:+ # Aha!'s only server-side time filter is `updated_since`, which keys off `updated_at`.+ # Advertising just `updated_at` keeps the user's chosen cursor aligned with what the API filters on.+ return [+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@dataclass+class AhaEndpointConfig:+ name: str+ path: str # Path under /api/v1, e.g. "/features"+ # Root key of the list in the JSON response. Usually equals `path` minus the slash, but Aha!+ # exposes to-dos under `/tasks` with a `tasks` root key, so it's declared explicitly.+ response_key: str+ # Aha! exposes `updated_since` (filters by `updated_at`) on this endpoint's list action.+ supports_incremental: bool+ # Stable creation-time field to partition by. None when the resource has no reliable created_at.+ partition_key: Optional[str] = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++AHA_ENDPOINTS: dict[str, AhaEndpointConfig] = {+ "products": AhaEndpointConfig(+ name="products",+ path="/products",+ response_key="products",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "features": AhaEndpointConfig(+ name="features",+ path="/features",+ response_key="features",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "epics": AhaEndpointConfig(+ name="epics",+ path="/epics",+ response_key="epics",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "initiatives": AhaEndpointConfig(+ name="initiatives",+ path="/initiatives",+ response_key="initiatives",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "ideas": AhaEndpointConfig(+ name="ideas",+ path="/ideas",+ response_key="ideas",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "goals": AhaEndpointConfig(+ name="goals",+ path="/goals",+ response_key="goals",+ # The Get goals list action documents no `updated_since` filter, so it's full refresh only.+ supports_incremental=False,+ ),+ "todos": AhaEndpointConfig(+ name="todos",+ path="/tasks",+ response_key="tasks",+ supports_incremental=True,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "users": AhaEndpointConfig(+ name="users",+ path="/users",+ response_key="users",+ # The Get users list action only documents an `email` filter — no time-based incremental.+ supports_incremental=False,+ ),+}++ENDPOINTS = tuple(AHA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in AHA_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.pyindex 63ab608ddca3..c9f1eaa2bdba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/source.py@@ -1,30 +1,159 @@-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.aha.aha import (+ AhaResumeConfig,+ aha_source,+ validate_credentials as validate_aha_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import (+ AHA_ENDPOINTS,+ 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AhaSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AhaSource(SimpleSource[AhaSourceConfig]):+class AhaSource(ResumableSource[AhaSourceConfig, AhaResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AHA+ @property+ def connection_host_fields(self) -> list[str]:+ # The API key is sent to `<subdomain>.aha.io`, so changing the subdomain must re-require it.+ return ["subdomain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AHA,category=DataWarehouseSourceCategory.PRODUCTIVITY,- label="Aha",+ label="Aha!",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Aha! account domain and API key to pull your Aha! data into the PostHog Data warehouse.++Create an API key under **Settings → Personal → Developer → API keys** in your Aha! account. The key inherits your account permissions, so it can read every record you can see.""",iconPath="/static/services/aha.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aha",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Account domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourcompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.aha.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never fix a credential/permission problem, so fail the sync. Match the+ # stable status text and `.aha.io` host, not the per-request path.+ "401 Client Error: Unauthorized": "Your Aha! API key is invalid or has been revoked. Create a new key in your Aha! account settings, then reconnect.",+ "403 Client Error: Forbidden": "Your Aha! API key is missing the permissions needed to sync this data. Check the key's account permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: AhaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = AHA_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: AhaSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ ok, status_code = validate_aha_credentials(config.subdomain, config.api_key)+ except ValueError as e:+ return False, str(e)++ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Aha! API key"+ return False, "Could not connect to Aha! with the provided account domain and API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AhaResumeConfig]:+ return ResumableSourceManager[AhaResumeConfig](inputs, AhaResumeConfig)++ def source_for_pipeline(+ self,+ config: AhaSourceConfig,+ resumable_source_manager: ResumableSourceManager[AhaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aha_source(+ subdomain=config.subdomain,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.pynew file mode 100644index 000000000000..b12efe036c91--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py@@ -0,0 +1,264 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.aha import aha+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.aha import (+ PER_PAGE,+ AhaResumeConfig,+ _build_initial_params,+ _build_url,+ _format_updated_since,+ _has_more_pages,+ get_rows,+ normalize_subdomain,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import AHA_ENDPOINTS+++class TestNormalizeSubdomain:+ @parameterized.expand(+ [+ ("bare", "acme", "acme"),+ ("full_host", "acme.aha.io", "acme"),+ ("https_url", "https://acme.aha.io", "acme"),+ ("trailing_slash", "acme.aha.io/", "acme"),+ ("with_hyphen", "acme-corp", "acme-corp"),+ ("whitespace", " acme ", "acme"),+ ]+ )+ def test_valid_subdomains(self, _name: str, value: str, expected: str) -> None:+ assert normalize_subdomain(value) == expected++ @parameterized.expand(+ [+ ("path_injection", "acme/../evil"),+ ("host_injection", "acme.evil.com"),+ ("userinfo_injection", "[email protected]"),+ ("empty", ""),+ ("space_inside", "ac me"),+ ("trailing_hyphen", "acme-"),+ ]+ )+ def test_invalid_subdomains_raise(self, _name: str, value: str) -> None:+ with pytest.raises(ValueError):+ normalize_subdomain(value)+++class TestFormatUpdatedSince:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ result = _format_updated_since(value)+ assert result == expected+ assert "+00:00" not in result+++class TestBuildInitialParams:+ def test_incremental_endpoint_with_cursor_adds_updated_since(self) -> None:+ params = _build_initial_params(+ AHA_ENDPOINTS["features"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert params == {"per_page": PER_PAGE, "updated_since": "2026-03-04T02:58:14Z"}++ def test_incremental_endpoint_without_cursor_omits_updated_since(self) -> None:+ params = _build_initial_params(+ AHA_ENDPOINTS["features"], should_use_incremental_field=True, db_incremental_field_last_value=None+ )+ assert params == {"per_page": PER_PAGE}++ def test_full_refresh_endpoint_never_filters(self) -> None:+ # goals has no server-side `updated_since`; a cursor must not leak into the request.+ params = _build_initial_params(+ AHA_ENDPOINTS["goals"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert params == {"per_page": PER_PAGE}+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert _build_url("https://acme.aha.io/api/v1", "/me", {}) == "https://acme.aha.io/api/v1/me"++ def test_encodes_params(self) -> None:+ url = _build_url(+ "https://acme.aha.io/api/v1", "/features", {"page": 2, "updated_since": "2026-03-04T02:58:14Z"}+ )+ assert url == "https://acme.aha.io/api/v1/features?page=2&updated_since=2026-03-04T02%3A58%3A14Z"+++class TestHasMorePages:+ @parameterized.expand(+ [+ ("more_pages", {"current_page": 1, "total_pages": 3}, 1, 200, True),+ ("last_page", {"current_page": 3, "total_pages": 3}, 3, 50, False),+ ("missing_meta_full_page", {}, 1, PER_PAGE, True),+ ("missing_meta_partial_page", {}, 1, 5, False),+ ]+ )+ def test_has_more(self, _name: str, pagination: dict, page: int, item_count: int, expected: bool) -> None:+ assert _has_more_pages(pagination, page, item_count) is expected+++class _FakeResumableManager:+ def __init__(self, state: AhaResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[AhaResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> AhaResumeConfig | None:+ return self._state++ def save_state(self, data: AhaResumeConfig) -> None:+ self.saved.append(data)+++class _FakeBatcher:+ """Yields one batch per item so save-after-yield behavior is observable without 2000+ rows."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._rows: list[dict] = []++ def batch(self, row: dict) -> None:+ self._rows.append(row)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._rows) > 0++ def get_table(self) -> list[dict]:+ rows = self._rows+ self._rows = []+ return rows+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ fetched.append(url)+ return pages[url]++ monkeypatch.setattr(aha, "_fetch_page", fake_fetch)+ return fetched+++def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ monkeypatch.setattr(aha, "Batcher", _FakeBatcher)+ rows: list[dict] = []+ for batch in get_rows(+ subdomain="acme",+ api_key="key",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestGetRows:+ def test_paginates_until_last_page(self, monkeypatch: Any) -> None:+ pages = {+ "https://acme.aha.io/api/v1/features?per_page=200&page=1": {+ "features": [{"id": "1"}, {"id": "2"}],+ "pagination": {"current_page": 1, "total_pages": 2},+ },+ "https://acme.aha.io/api/v1/features?per_page=200&page=2": {+ "features": [{"id": "3"}],+ "pagination": {"current_page": 2, "total_pages": 2},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="features")++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ assert fetched == list(pages)++ def test_saves_resume_state_after_each_yielded_page(self, monkeypatch: Any) -> None:+ pages = {+ "https://acme.aha.io/api/v1/features?per_page=200&page=1": {+ "features": [{"id": "1"}],+ "pagination": {"current_page": 1, "total_pages": 2},+ },+ "https://acme.aha.io/api/v1/features?per_page=200&page=2": {+ "features": [{"id": "2"}],+ "pagination": {"current_page": 2, "total_pages": 2},+ },+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ _collect(monkeypatch, manager, endpoint="features")++ # State is saved only while more pages remain (page 1 -> next_page 2), never on the last page.+ assert manager.saved == [AhaResumeConfig(next_page=2)]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ pages = {+ "https://acme.aha.io/api/v1/features?per_page=200&page=2": {+ "features": [{"id": "2"}],+ "pagination": {"current_page": 2, "total_pages": 2},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(AhaResumeConfig(next_page=2)), endpoint="features")++ assert [r["id"] for r in rows] == ["2"]+ assert fetched == ["https://acme.aha.io/api/v1/features?per_page=200&page=2"]++ def test_incremental_cursor_added_to_request(self, monkeypatch: Any) -> None:+ pages = {+ "https://acme.aha.io/api/v1/features?per_page=200&updated_since=2026-03-04T02%3A58%3A14Z&page=1": {+ "features": [{"id": "1"}],+ "pagination": {"current_page": 1, "total_pages": 1},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="features",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert "updated_since=2026-03-04T02%3A58%3A14Z" in fetched[0]++ def test_uses_response_key_for_todos(self, monkeypatch: Any) -> None:+ # to-dos live at /tasks with a `tasks` root key.+ pages = {+ "https://acme.aha.io/api/v1/tasks?per_page=200&page=1": {+ "tasks": [{"id": "t1"}],+ "pagination": {"current_page": 1, "total_pages": 1},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="todos")++ assert [r["id"] for r in rows] == ["t1"]+ assert fetched == ["https://acme.aha.io/api/v1/tasks?per_page=200&page=1"]++ def test_stops_on_empty_page(self, monkeypatch: Any) -> None:+ pages = {+ "https://acme.aha.io/api/v1/goals?per_page=200&page=1": {+ "goals": [],+ "pagination": {"current_page": 1, "total_pages": 1},+ },+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="goals")++ assert rows == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha_source.pynew file mode 100644index 000000000000..90a58efb4df7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha_source.py@@ -0,0 +1,165 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.aha.aha import AhaResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import AHA_ENDPOINTS, ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.source import AhaSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AhaSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++# Endpoints whose Aha! list action exposes the server-side `updated_since` filter.+_INCREMENTAL_ENDPOINTS = {"products", "features", "epics", "initiatives", "ideas", "todos"}+_FULL_REFRESH_ENDPOINTS = {"goals", "users"}+++class TestAhaSource:+ def setup_method(self):+ self.source = AhaSource()+ self.team_id = 123+ self.config = AhaSourceConfig(subdomain="acme", api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.AHA++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Aha"+ assert config.label == "Aha!"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/aha.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aha"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["subdomain", "api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_subdomain_listed_as_connection_host_field(self):+ # The API key is sent to <subdomain>.aha.io, so retargeting the subdomain must re-require it.+ assert self.source.connection_host_fields == ["subdomain"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://acme.aha.io/api/v1/features?page=1&per_page=200",+ "403 Client Error: Forbidden for url: https://acme.aha.io/api/v1/ideas?page=1&per_page=200",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://acme.aha.io/api/v1/features",+ "500 Server Error: Internal Server Error for url: https://acme.aha.io/api/v1/features",+ "HTTPSConnectionPool(host='acme.aha.io', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["updated_at"]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["features"])+ assert len(schemas) == 1+ assert schemas[0].name == "features"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(AHA_ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Aha! API key"),+ ((False, 403), False, "Could not connect to Aha! with the provided account domain and API key"),+ ((False, None), False, "Could not connect to Aha! with the provided account domain and API key"),+ ],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.aha.source.validate_aha_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("acme", "key")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.aha.source.validate_aha_credentials")+ def test_validate_credentials_surfaces_bad_subdomain(self, mock_validate):+ mock_validate.side_effect = ValueError("Invalid Aha! account domain: 'a/b'.")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "Invalid Aha! account domain" in (error_message or "")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is AhaResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.aha.source.aha_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_aha_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "features"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "updated_at"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_aha_source.assert_called_once()+ kwargs = mock_aha_source.call_args.kwargs+ assert kwargs["subdomain"] == "acme"+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "features"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.aha.source.aha_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_aha_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_aha_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 81e2a5dfd6b4..99700c1785ff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -170,7 +170,8 @@ class AgileCRMSourceConfig(config.Config):@config.configclass AhaSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str@config.config