: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 chameleon import source (#66741)
Tom Owers9984d83136e9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 099bc5587e55..f0e2a783a144 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -87,6 +87,7 @@ the row lists both.| campayn | HTTP | requests | ✅ || canny | HTTP | requests | ✅ || care_quality_commission | HTTP | requests | ✅ |+| chameleon | HTTP | requests | ✅ || chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ || chargedesk | HTTP | requests | ✅ || checkout_com | HTTP | requests | ✅ |@@ -345,7 +346,6 @@ doesn't conflict with concurrent PRs.- captain_data- cart_com- castor_edc-- chameleon- chargify- chatwoot- chiftdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/canonical_descriptions.pynew file mode 100644index 000000000000..5d7d7f363193--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/canonical_descriptions.py@@ -0,0 +1,159 @@+"""Canonical, documentation-sourced descriptions for Chameleon endpoints and columns.++Sourced from the official Chameleon API reference (https://developers.chameleon.io). Keyed by the+endpoint names in `settings.py` `CHAMELEON_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Chameleon table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Every Chameleon model carries these.+_ID = "The Chameleon ID (a globally-unique, time-ordered ObjectId)."+_CREATED_AT = "Time at which this record was created or first added to Chameleon."+_UPDATED_AT = "Time at which any property of this record was last updated."++_EXPERIENCE_STATS = {+ "stats": "Aggregated all-time statistics for this Experience.",+ "stats.started_count": "Number of end-users who saw this Experience.",+ "stats.last_started_at": "Most recent time any user saw this Experience.",+ "stats.completed_count": "Number of end-users who completed/finished this Experience.",+ "stats.last_completed_at": "Most recent time any user completed/finished this Experience.",+ "stats.exited_count": "Number of end-users who dismissed/exited this Experience.",+ "stats.last_exited_at": "Most recent time any user dismissed/exited this Experience.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "profiles": {+ "description": "A User Profile: one of your product's identified end-users, with the properties Chameleon has stored about them.",+ "docs_url": "https://developers.chameleon.io/apis/profiles",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "updated_at": _UPDATED_AT,+ "uid": "The external user ID that came from your backend system.",+ "company_id": "The Chameleon ID of the Company this user is associated with, if any.",+ "browser_x": "Browser width in pixels.",+ "browser_tz": "Browser timezone as an integer offset from UTC.",+ "browser_l": "Language code reported by the Accept-Language header.",+ "browser_n": "Browser name (chrome, firefox, safari, opera, ie10, ie11, or edge).",+ "browser_k": "Browser kind (desktop or mobile).",+ "percent": "A randomly assigned but stable value used for A/B testing.",+ "last_seen_at": "When the user was last active on a page where Chameleon is installed.",+ "last_seen_session_count": "Number of sessions (a session ends after 90 minutes of inactivity).",+ "delivery_ids": "Ordered list of Delivery model IDs for this user.",+ },+ },+ "companies": {+ "description": "A Company (account): one of your identified customer accounts, with the properties Chameleon has stored about it.",+ "docs_url": "https://developers.chameleon.io/apis/companies",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "uid": "The external company ID that came from your backend system.",+ },+ },+ "segments": {+ "description": "A Segment: a reusable set of user-targeting filters used to decide which users see which Experiences.",+ "docs_url": "https://developers.chameleon.io/apis/segments",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "updated_at": _UPDATED_AT,+ "name": "The name given to the Segment by a Chameleon administrator.",+ "items": "The array of Segmentation Filter expressions that define this Segment.",+ "items_op": "How the filter items are joined: 'and' or 'or'.",+ },+ },+ "tours": {+ "description": "A Tour: a sequence of steps shown to end-users who match the configured targeting criteria.",+ "docs_url": "https://developers.chameleon.io/apis/tours",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "updated_at": _UPDATED_AT,+ "name": "The name given to the Tour by a Chameleon administrator.",+ "style": "The delivery method of this Tour: 'auto' or 'manual'.",+ "position": "The order this appears in lists (starting from 0).",+ "experiment_at": "When A/B experimentation was turned on for this Tour.",+ "experiment_range": "The range of Profile#percent included in the experiment.",+ "segment_ids": "The Chameleon IDs of the Segments targeted by this Tour.",+ "published_at": "The time this Tour was most recently published.",+ "tag_ids": "The Chameleon IDs of the Tags attached to this Tour.",+ "dashboard_url": "Direct link to this Tour in the Chameleon Dashboard.",+ **_EXPERIENCE_STATS,+ },+ },+ "surveys": {+ "description": "A Microsurvey: an in-product question step used to collect contextual user feedback.",+ "docs_url": "https://developers.chameleon.io/apis/surveys",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "updated_at": _UPDATED_AT,+ "name": "The name given to the Microsurvey by a Chameleon administrator.",+ "position": "The order this appears in lists (starting from 0).",+ "segment_ids": "The Chameleon IDs of the Segments targeted by this Microsurvey.",+ "published_at": "The time this Microsurvey was most recently published.",+ "tag_ids": "The Chameleon IDs of the Tags attached to this Microsurvey.",+ "experiment_at": "When A/B experimentation was turned on for this Microsurvey.",+ "dashboard_url": "Direct link to this Microsurvey in the Chameleon Dashboard.",+ "last_dropdown_items": "All dropdown options that have been selected by any user.",+ **_EXPERIENCE_STATS,+ },+ },+ "launchers": {+ "description": "A Launcher: a menu of items (Tours, surveys, links) shown to end-users who match the configured criteria.",+ "docs_url": "https://developers.chameleon.io/apis/launchers",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "updated_at": _UPDATED_AT,+ "name": "The name given to the Launcher by a Chameleon administrator.",+ "title": "The display title.",+ "description": "The display description.",+ "preset": "The preconfigured type (icon, element, icon_checklist, updates, or faqs).",+ "segment_ids": "The Chameleon IDs of the Segments targeted by this Launcher.",+ "published_at": "The time this Launcher was most recently published.",+ "tag_ids": "The Chameleon IDs of the Tags attached to this Launcher.",+ "list_type": "Whether this is a checklist or a normal list (default or checklist).",+ "items": "The array of items that define the Launcher menu contents.",+ },+ },+ "event_names": {+ "description": "An Event Name: a tracked or custom event configured in your Chameleon account, usable in Segmentation filters.",+ "docs_url": "https://developers.chameleon.io/apis/event-names",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "updated_at": _UPDATED_AT,+ "name": "The display name given to the event by a Chameleon administrator.",+ "description": "A description of the event.",+ "uid": "The normalized identifier for the event (e.g. 'Signed up' becomes 'signed_up').",+ "kind": "The kind of event: 'tracked' or 'custom'.",+ "source": "The source of the event (api_js, api_v3, segment, freshpaint, heap, mixpanel, rudderstack, or amplitude).",+ "published_at": "When this event was set to be a Tracked event. Null if not actively tracked.",+ "last_seen_at": "When this event was last triggered by any user.",+ "dashboard_url": "Direct link to this Event Name in the Chameleon Dashboard.",+ },+ },+ "responses": {+ "description": "A Microsurvey response: a single user's interaction with a Microsurvey, including buttons clicked and text entered.",+ "docs_url": "https://developers.chameleon.io/apis/survey-responses",+ "columns": {+ "id": _ID,+ "created_at": _CREATED_AT,+ "updated_at": _UPDATED_AT,+ "survey_id": "The Chameleon ID of the Microsurvey this response belongs to.",+ "profile_id": "The Chameleon ID of the User Profile that submitted this response.",+ "href": "The page URL where the Microsurvey was displayed.",+ "button_text": "The text of the button that was clicked.",+ "button_order": "The 0-indexed position of the button that was clicked.",+ "button_id": "The Chameleon ID of the button that was clicked.",+ "input_text": "Free-text comment left by the user on the first step or follow-up question 1.",+ "dropdown_items": "The selected dropdown options on the first step.",+ "finished_at": "When the last step of the Microsurvey response was completed.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/chameleon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/chameleon.pynew file mode 100644index 000000000000..b36f5f9f14ca--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/chameleon.py@@ -0,0 +1,264 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+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.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.settings import (+ CHAMELEON_ENDPOINTS,+ ChameleonEndpointConfig,+)+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++# Single base URL for every account — Chameleon has no per-account hostname.+CHAMELEON_BASE_URL = "https://api.chameleon.io/v3"+# The account-secret probe hits the root, which echoes back the account/user ids on success.+CHAMELEON_ROOT_URL = "https://api.chameleon.io"+++class ChameleonRetryableError(Exception):+ pass+++class ChameleonResumeConfig:+ # Cursor for the next page: the `cursor.before` id from the previous response. None starts at page one.+ before: str | None = None+ # The Microsurvey currently being paged through, for the `responses` fan-out. A stable survey-id+ # bookmark (not a positional index) so surveys added/removed between a crash and the retry can't+ # resume us into the wrong survey. None for the standard (non-fan-out) endpoints.+ survey_id: str | None = None+++def _get_headers(account_secret: str) -> dict[str, str]:+ return {"X-Account-Secret": account_secret, "Accept": "application/json"}+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ if not params:+ return base_url+ return f"{base_url}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type((ChameleonRetryableError, 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[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ # 429 (rate limited) and 5xx are transient — retry. Chameleon returns rate-limit wait hints in+ # X-Retry-After / X-Ratelimit-Wait headers; the exponential backoff below covers them conservatively.+ if response.status_code == 429 or response.status_code >= 500:+ raise ChameleonRetryableError(f"Chameleon API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 is expected and handled during the responses fan-out (a survey deleted mid-sync).+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Chameleon API error: status={response.status_code}, body={response.text[:200]!r}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(account_secret: str) -> tuple[bool, str | None]:+ # The root probe echoes back the account/user ids on success (200). A bad or revoked secret is+ # rejected with 401/403 — those are the only conclusive "invalid" signals. Transport failures and+ # unexpected statuses (429, 5xx) are inconclusive: reporting them as an invalid secret would push+ # users to needlessly rotate a working credential, so they get a generic retry message instead.+ # `redact_values` masks the secret from any captured sample.+ try:+ response = make_tracked_session(redact_values=(account_secret,)).get(+ CHAMELEON_ROOT_URL, headers=_get_headers(account_secret), timeout=10+ )+ except requests.RequestException:+ return False, "Could not reach Chameleon to validate the account secret. Please try again."+ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Chameleon account secret"+ return (+ False,+ f"Chameleon could not validate the account secret right now (status {response.status_code}). Please try again.",+ )+++def _iter_pages(+ session: requests.Session,+ url: str,+ data_key: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ base_params: dict[str, Any],+ start_before: str | None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Page a Chameleon list endpoint, yielding (rows, next_before) per page.++ Chameleon returns records newest-first and paginates with a `cursor.before` id pointing at the+ oldest record on the page; the next page is fetched with `before=<that id>`. Pagination stops once+ a page is empty, the cursor is exhausted, or the cursor fails to advance (a defensive guard against+ an unexpected repeated cursor wedging the sync in an infinite loop).+ """+ before = start_before+ while True:+ params = dict(base_params)+ if before:+ params["before"] = before++ data = _fetch_page(session, _build_url(url, params), headers, logger)+ rows = data.get(data_key, [])+ next_before = (data.get("cursor") or {}).get("before")++ yield rows, next_before++ if not rows or not next_before or next_before == before:+ break+ before = next_before+++def _iter_survey_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:+ config = CHAMELEON_ENDPOINTS["surveys"]+ for rows, _ in _iter_pages(+ session,+ f"{CHAMELEON_BASE_URL}{config.path}",+ config.data_key,+ headers,+ logger,+ {"limit": config.page_size},+ start_before=None,+ ):+ for survey in rows:+ yield survey["id"]+++def _get_response_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChameleonResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every Microsurvey, listing its responses and stamping the parent `survey_id`.++ /analyze/responses requires an `id` (the Microsurvey id), so responses can only be pulled per+ survey. Full refresh — re-pulled rows on resume are deduped by the `id` primary key on merge.+ """+ config = CHAMELEON_ENDPOINTS["responses"]+ survey_ids = list(_iter_survey_ids(session, headers, logger))++ # Resolve the saved survey-id bookmark to the slice of surveys still to process. If the bookmarked+ # survey no longer exists (deleted between runs), start over from the first survey — merge dedupes+ # the re-pulled rows on the primary key. `resume_before` is consumed by the first survey only.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = survey_ids+ resume_before: str | None = None+ if resume is not None and resume.survey_id is not None and resume.survey_id in survey_ids:+ remaining = survey_ids[survey_ids.index(resume.survey_id) :]+ resume_before = resume.before+ logger.debug(f"Chameleon: resuming responses from survey_id={resume.survey_id}, before={resume_before}")++ for index, survey_id in enumerate(remaining):+ start_before = resume_before+ resume_before = None # only the resumed-into survey uses the saved cursor; the rest start fresh++ try:+ for rows, next_before in _iter_pages(+ session,+ f"{CHAMELEON_BASE_URL}{config.path}",+ config.data_key,+ headers,+ logger,+ {"id": survey_id, "limit": config.page_size},+ start_before,+ ):+ if rows:+ yield [{**row, "survey_id": survey_id} for row in rows]+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the+ # last page rather than skipping it — merge dedupes on the primary key.+ if next_before:+ resumable_source_manager.save_state(+ ChameleonResumeConfig(before=next_before, survey_id=survey_id)+ )+ except requests.HTTPError as exc:+ # A survey deleted between enumeration and this fetch 404s. Skip it rather than failing the+ # whole sync — the responses are genuinely gone. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Chameleon: survey {survey_id} not found while fetching responses, skipping")+ else:+ raise++ # Advance the bookmark to the next survey so a crash between surveys resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(ChameleonResumeConfig(before=None, survey_id=remaining[index + 1]))+++def get_rows(+ account_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChameleonResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = CHAMELEON_ENDPOINTS[endpoint]+ headers = _get_headers(account_secret)+ # One session reused across every page (and, for fan-out, every survey) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. The account secret rides in a custom+ # `X-Account-Secret` header the name-based scrubbers don't recognise, so redact it explicitly.+ session = make_tracked_session(redact_values=(account_secret,))++ if config.fan_out_over_surveys:+ yield from _get_response_rows(session, headers, logger, resumable_source_manager)+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_before = resume.before if resume is not None else None+ if start_before:+ logger.debug(f"Chameleon: resuming {endpoint} from before={start_before}")++ for rows, next_before in _iter_pages(+ session,+ f"{CHAMELEON_BASE_URL}{config.path}",+ config.data_key,+ headers,+ logger,+ {"limit": config.page_size},+ start_before,+ ):+ if rows:+ yield rows+ if next_before:+ resumable_source_manager.save_state(ChameleonResumeConfig(before=next_before))+++def chameleon_source(+ account_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChameleonResumeConfig],+) -> SourceResponse:+ endpoint_config: ChameleonEndpointConfig = CHAMELEON_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ account_secret=account_secret,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ # Chameleon returns records most-recently-created first.+ sort_mode="desc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/settings.pynew file mode 100644index 000000000000..654a1818bdf8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/settings.py@@ -0,0 +1,39 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class ChameleonEndpointConfig:+ name: str+ # Path appended to the v3 base URL, e.g. "/analyze/profiles" or "/edit/segments".+ path: str+ # Top-level key in the JSON response that holds the list of records. Chameleon names it after the+ # plural resource (e.g. {"segments": [...], "cursor": {...}}), which matches the endpoint name today.+ data_key: str+ partition_key: Optional[str] = "created_at" # stable creation timestamp present on every model+ page_size: int = 500 # Chameleon caps `limit` at 500+ primary_keys: list[str] = field(default_factory=lambda: ["id"]) # Chameleon IDs are globally-unique ObjectIds+ should_sync_default: bool = True+ # Microsurvey responses can only be listed per-survey (the `id` param is required), so this endpoint+ # fans out over every Microsurvey and stamps the parent `survey_id` onto each row.+ fan_out_over_surveys: bool = False+++CHAMELEON_ENDPOINTS: dict[str, ChameleonEndpointConfig] = {+ "profiles": ChameleonEndpointConfig(name="profiles", path="/analyze/profiles", data_key="profiles"),+ "companies": ChameleonEndpointConfig(name="companies", path="/analyze/companies", data_key="companies"),+ "segments": ChameleonEndpointConfig(name="segments", path="/edit/segments", data_key="segments"),+ "tours": ChameleonEndpointConfig(name="tours", path="/edit/tours", data_key="tours"),+ "surveys": ChameleonEndpointConfig(name="surveys", path="/edit/surveys", data_key="surveys"),+ "launchers": ChameleonEndpointConfig(name="launchers", path="/edit/launchers", data_key="launchers"),+ "event_names": ChameleonEndpointConfig(name="event_names", path="/edit/event_names", data_key="event_names"),+ # Fan-out child: one paginated request per Microsurvey against /analyze/responses?id=<survey_id>.+ "responses": ChameleonEndpointConfig(+ name="responses",+ path="/analyze/responses",+ data_key="responses",+ fan_out_over_surveys=True,+ ),+}++ENDPOINTS = tuple(CHAMELEON_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/source.pyindex dc09d9dbb5a2..a6c2948f7e07 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/source.py@@ -1,19 +1,42 @@-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.chameleon.chameleon import (+ ChameleonResumeConfig,+ chameleon_source,+ validate_credentials as validate_chameleon_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.settings import (+ CHAMELEON_ENDPOINTS,+ ENDPOINTS,+)+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 ChameleonSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ChameleonSource(SimpleSource[ChameleonSourceConfig]):+class ChameleonSource(ResumableSource[ChameleonSourceConfig, ChameleonResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CHAMELEON@@ -24,7 +47,94 @@ class ChameleonSource(SimpleSource[ChameleonSourceConfig]):name=SchemaExternalDataSourceType.CHAMELEON,category=DataWarehouseSourceCategory.ANALYTICS,label="Chameleon",- iconPath="/static/services/chameleon.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Chameleon API secret to automatically pull your Chameleon data into the PostHog Data warehouse.++You can generate an account-specific API secret in your [Chameleon account settings](https://app.chameleon.io/settings/tokens). The secret is only shown once, so copy it when you create it.""",+ iconPath="/static/services/chameleon.png",+ docsUrl="https://posthog.com/docs/cdp/sources/chameleon",+ keywords=["chameleon.io", "onboarding", "product adoption", "tours"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="account_secret",+ label="Account secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Chameleon account secret",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Chameleon returns 403 (not 401) for an invalid or revoked account secret. It surfaces as a+ # requests HTTPError when `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy+ # a credential problem, so stop the sync. Match the stable status text and base host.+ "403 Client Error: Forbidden for url: https://api.chameleon.io": "Your Chameleon account secret is invalid or has been revoked. Generate a new secret in your Chameleon account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: ChameleonSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "responses":+ return "Microsurvey responses, fanned out across every Microsurvey. Full refresh only"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = CHAMELEON_ENDPOINTS[endpoint]+ # Chameleon's only server-side time filter (`after`) keys on creation time, so it can't catch+ # updates to existing records. We ship every endpoint as full refresh until incremental+ # semantics are verified against a live account.+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ )++ 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: ChameleonSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_chameleon_credentials(config.account_secret)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ChameleonResumeConfig]:+ return ResumableSourceManager[ChameleonResumeConfig](inputs, ChameleonResumeConfig)++ def source_for_pipeline(+ self,+ config: ChameleonSourceConfig,+ resumable_source_manager: ResumableSourceManager[ChameleonResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return chameleon_source(+ account_secret=config.account_secret,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/tests/test_chameleon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/tests/test_chameleon.pynew file mode 100644index 000000000000..85208761f94b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/tests/test_chameleon.py@@ -0,0 +1,241 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon import chameleon+from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.chameleon import (+ ChameleonResumeConfig,+ _build_url,+ chameleon_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.settings import CHAMELEON_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: ChameleonResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ChameleonResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ChameleonResumeConfig | None:+ return self._state++ def save_state(self, data: ChameleonResumeConfig) -> None:+ self.saved.append(data)+++def _response_with_status(status_code: int) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ return response+++def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str = "responses"+) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(chameleon, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for batch in get_rows(+ account_secret="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestBuildUrl:+ def test_no_params_returns_base(self) -> None:+ assert (+ _build_url("https://api.chameleon.io/v3/edit/segments", {}) == "https://api.chameleon.io/v3/edit/segments"+ )++ def test_encodes_params(self) -> None:+ url = _build_url("https://api.chameleon.io/v3/analyze/responses", {"id": "S1", "limit": 500})+ assert url == "https://api.chameleon.io/v3/analyze/responses?id=S1&limit=500"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Chameleon account secret"),+ ("forbidden", 403, False, "Invalid Chameleon account secret"),+ ("rate_limited", 429, False, "status 429"),+ ("server_error", 500, False, "status 500"),+ ]+ )+ def test_status_maps_to_result(+ self, _name: str, status_code: int, expected_ok: bool, expected_fragment: str | None+ ) -> None:+ with patch.object(chameleon, "make_tracked_session") as make_session:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ make_session.return_value = session+ ok, error = validate_credentials("secret")+ assert ok is expected_ok+ if expected_fragment is None:+ assert error is None+ else:+ assert error is not None and expected_fragment in error++ def test_network_error_is_inconclusive(self) -> None:+ with patch.object(chameleon, "make_tracked_session") as make_session:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ make_session.return_value = session+ ok, error = validate_credentials("secret")+ assert ok is False+ assert error is not None and "Could not reach Chameleon" in error+++class TestStandardEndpointPagination:+ def test_follows_before_cursor_until_exhausted(self, monkeypatch: Any) -> None:+ base = "https://api.chameleon.io/v3/edit/segments?limit=500"+ page2 = "https://api.chameleon.io/v3/edit/segments?limit=500&before=S2"+ pages = {+ base: {"segments": [{"id": "S1"}, {"id": "S2"}], "cursor": {"limit": 500, "before": "S2"}},+ page2: {"segments": [{"id": "S3"}], "cursor": {"limit": 500, "before": "S3"}},+ "https://api.chameleon.io/v3/edit/segments?limit=500&before=S3": {"segments": [], "cursor": {}},+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "segments")+ assert [r["id"] for r in rows] == ["S1", "S2", "S3"]++ def test_stops_when_cursor_missing(self, monkeypatch: Any) -> None:+ base = "https://api.chameleon.io/v3/edit/tours?limit=500"+ pages = {base: {"tours": [{"id": "T1"}], "cursor": {}}}+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "tours")+ assert [r["id"] for r in rows] == ["T1"]++ def test_saves_resume_state_after_each_page_with_more_to_come(self, monkeypatch: Any) -> None:+ base = "https://api.chameleon.io/v3/edit/segments?limit=500"+ page2 = "https://api.chameleon.io/v3/edit/segments?limit=500&before=S2"+ pages = {+ base: {"segments": [{"id": "S1"}, {"id": "S2"}], "cursor": {"before": "S2"}},+ page2: {"segments": [{"id": "S3"}], "cursor": {}},+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, pages, "segments")+ # Only the first page has a `next_before`, so exactly one checkpoint is saved, pointing at it.+ assert manager.saved == [ChameleonResumeConfig(before="S2")]++ def test_resumes_from_saved_before(self, monkeypatch: Any) -> None:+ # When state exists, the first request must start from the saved cursor, not page one.+ resume_url = "https://api.chameleon.io/v3/edit/segments?limit=500&before=S2"+ pages = {resume_url: {"segments": [{"id": "S3"}], "cursor": {}}}+ manager = _FakeResumableManager(ChameleonResumeConfig(before="S2"))+ rows = _collect(manager, monkeypatch, pages, "segments")+ assert [r["id"] for r in rows] == ["S3"]+++class TestResponsesFanOut:+ def test_fans_out_over_surveys_and_stamps_survey_id(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.chameleon.io/v3/edit/surveys?limit=500": {+ "surveys": [{"id": "SV1"}, {"id": "SV2"}],+ "cursor": {},+ },+ "https://api.chameleon.io/v3/analyze/responses?id=SV1&limit=500": {+ "responses": [{"id": "R1"}, {"id": "R2"}],+ "cursor": {},+ },+ "https://api.chameleon.io/v3/analyze/responses?id=SV2&limit=500": {+ "responses": [{"id": "R3"}],+ "cursor": {},+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [+ {"id": "R1", "survey_id": "SV1"},+ {"id": "R2", "survey_id": "SV1"},+ {"id": "R3", "survey_id": "SV2"},+ ]++ def test_paginates_within_a_survey(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.chameleon.io/v3/edit/surveys?limit=500": {"surveys": [{"id": "SV1"}], "cursor": {}},+ "https://api.chameleon.io/v3/analyze/responses?id=SV1&limit=500": {+ "responses": [{"id": "R1"}],+ "cursor": {"before": "R1"},+ },+ "https://api.chameleon.io/v3/analyze/responses?id=SV1&limit=500&before=R1": {+ "responses": [{"id": "R2"}],+ "cursor": {},+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages)+ assert [r["id"] for r in rows] == ["R1", "R2"]++ def test_survey_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:+ not_found = requests.HTTPError(response=_response_with_status(404))+ pages = {+ "https://api.chameleon.io/v3/edit/surveys?limit=500": {+ "surveys": [{"id": "SV1"}, {"id": "GONE"}, {"id": "SV2"}],+ "cursor": {},+ },+ "https://api.chameleon.io/v3/analyze/responses?id=SV1&limit=500": {+ "responses": [{"id": "R1"}],+ "cursor": {},+ },+ "https://api.chameleon.io/v3/analyze/responses?id=GONE&limit=500": not_found,+ "https://api.chameleon.io/v3/analyze/responses?id=SV2&limit=500": {+ "responses": [{"id": "R2"}],+ "cursor": {},+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, pages)+ assert [r["id"] for r in rows] == ["R1", "R2"]++ def test_non_404_http_error_propagates(self, monkeypatch: Any) -> None:+ server_error = requests.HTTPError(response=_response_with_status(500))+ pages = {+ "https://api.chameleon.io/v3/edit/surveys?limit=500": {"surveys": [{"id": "SV1"}], "cursor": {}},+ "https://api.chameleon.io/v3/analyze/responses?id=SV1&limit=500": server_error,+ }+ with pytest.raises(requests.HTTPError):+ _collect(_FakeResumableManager(), monkeypatch, pages)++ def test_resume_from_deleted_survey_restarts_from_first(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.chameleon.io/v3/edit/surveys?limit=500": {"surveys": [{"id": "SV1"}], "cursor": {}},+ "https://api.chameleon.io/v3/analyze/responses?id=SV1&limit=500": {+ "responses": [{"id": "R1"}],+ "cursor": {},+ },+ }+ manager = _FakeResumableManager(ChameleonResumeConfig(before=None, survey_id="DELETED"))+ rows = _collect(manager, monkeypatch, pages)+ assert [r["id"] for r in rows] == ["R1"]+++class TestChameleonSourceResponse:+ @parameterized.expand(list(CHAMELEON_ENDPOINTS.keys()))+ def test_source_response_shape(self, endpoint: str) -> None:+ response = chameleon_source(+ account_secret="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Chameleon returns newest-first; the watermark/ordering contract must reflect that.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/tests/test_chameleon_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/tests/test_chameleon_source.pynew file mode 100644index 000000000000..41de3d093da1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chameleon/tests/test_chameleon_source.py@@ -0,0 +1,130 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.chameleon import ChameleonResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.chameleon.source import ChameleonSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(secret: str = "secret") -> MagicMock:+ config = MagicMock()+ config.account_secret = secret+ return config+++class TestChameleonSourceConfig:+ def setup_method(self) -> None:+ self.source = ChameleonSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CHAMELEON++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static endpoint catalog with no I/O, so the public docs can render it.+ assert self.source.lists_tables_without_credentials is True++ def test_single_secret_field_is_a_required_password(self) -> None:+ fields = self.source.get_source_config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "account_secret"+ assert field.required is True+ assert field.type.value == "password"+ assert field.secret is True++ def test_docs_url_matches_doc_filename(self) -> None:+ assert self.source.get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/chameleon"++ def test_stays_unreleased_alpha(self) -> None:+ config = self.source.get_source_config+ assert config.unreleasedSource is True+ assert config.releaseStatus is not None+ assert config.releaseStatus.value == "alpha"+++class TestChameleonSchemas:+ def setup_method(self) -> None:+ self.source = ChameleonSource()++ def test_lists_every_endpoint_as_full_refresh(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_names_filter_narrows_output(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=1, names=["tours"])+ assert [s.name for s in schemas] == ["tours"]++ def test_responses_describes_fan_out(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=1)}+ assert "Full refresh" in (schemas["responses"].description or "")+++class TestChameleonCredentials:+ def setup_method(self) -> None:+ self.source = ChameleonSource()++ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid", (False, "Invalid Chameleon account secret")),+ ("unreachable", (False, "Could not reach Chameleon to validate the account secret. Please try again.")),+ ]+ )+ def test_validate_credentials_propagates_probe_result(+ self, _name: str, probe_result: tuple[bool, str | None]+ ) -> None:+ with patch.object(source_module, "validate_chameleon_credentials", return_value=probe_result):+ result = self.source.validate_credentials(_config(), team_id=1)+ assert result == probe_result++ def test_403_is_non_retryable(self) -> None:+ observed = "403 Client Error: Forbidden for url: https://api.chameleon.io/v3/edit/segments?limit=500"+ assert any(key in observed for key in self.source.get_non_retryable_errors())++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.chameleon.io/v3/edit/tours"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.chameleon.io"),+ ("read_timeout", "HTTPSConnectionPool(host='api.chameleon.io', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:+ assert not any(key in observed for key in self.source.get_non_retryable_errors())+++class TestChameleonPipelineWiring:+ def setup_method(self) -> None:+ self.source = ChameleonSource()++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ChameleonResumeConfig++ def test_source_for_pipeline_passes_secret_and_schema_through(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "profiles"+ manager = MagicMock()+ with patch.object(source_module, "chameleon_source") as chameleon_source_mock:+ self.source.source_for_pipeline(_config("my-secret"), manager, inputs)+ chameleon_source_mock.assert_called_once_with(+ account_secret="my-secret",+ endpoint="profiles",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(ENDPOINTS).issubset(set(descriptions))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex b45b55463b57..f904448d7617 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@@ -599,7 +599,7 @@ class CastorEDCSourceConfig(config.Config):@config.configclass ChameleonSourceConfig(config.Config):- pass+ account_secret: str@config.config