: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 charthop import source (#69615)
Tom Owers330ab3d8d8fc
diff --git a/frontend/public/services/charthop.png b/frontend/public/services/charthop.pngnew file mode 100644index 000000000000..db41de2a8aafBinary files /dev/null and b/frontend/public/services/charthop.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ebaa4bac7cde..13e1fbca5905 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -96,6 +96,7 @@ the row lists both.| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ || chargedesk | HTTP | requests | ✅ || chargify | HTTP | requests + `rest_source.RESTClient` | ✅ |+| charthop | HTTP | requests | ✅ || checkout_com | HTTP | requests | ✅ || churnkey | HTTP | requests | ✅ || coassemble | HTTP | requests | ✅ |@@ -482,7 +483,6 @@ doesn't conflict with concurrent PRs.- captain_data- cart_com- castor_edc-- charthop- chatwoot- chift- chorusdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/canonical_descriptions.pynew file mode 100644index 000000000000..0d00f56afe70--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/canonical_descriptions.py@@ -0,0 +1,158 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the official ChartHop API reference (https://api.charthop.com/swagger).+# Person, job, and group rows are field-based (including org-specific custom fields), so only their+# well-known base columns are described; the rest fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "persons": {+ "description": "People in the organization, including ex-employees, one row per person.",+ "docs_url": "https://api.charthop.com/swagger#/person/findPersons",+ "columns": {+ "id": "Globally unique id of the person.",+ "name": "Person's name, with first/middle/last/pref components.",+ "contact": "Contact details such as work and home email.",+ },+ },+ "jobs": {+ "description": "Jobs (filled and open positions) in the organization, one row per job.",+ "docs_url": "https://api.charthop.com/swagger#/job/findJobs",+ "columns": {+ "id": "Globally unique id of the job.",+ "title": "Job title.",+ "open": "Whether the job is an open position or filled.",+ },+ },+ "groups": {+ "description": "Groups in the organization, such as departments and teams, one row per group.",+ "docs_url": "https://api.charthop.com/swagger#/group/findGroups",+ "columns": {+ "id": "Globally unique id of the group.",+ "name": "Name of the group.",+ "type": "Group type the group belongs to (e.g. department, team).",+ },+ },+ "group_types": {+ "description": "Group types configured for the organization (e.g. department, team, location).",+ "docs_url": "https://api.charthop.com/swagger#/group-type/findGroupTypes",+ "columns": {+ "id": "Globally unique id.",+ "orgId": "Parent organization id.",+ "name": "Unique name of the group type.",+ "fieldName": "Field name for the field representing membership in this type of group.",+ "code": "External code identifier of the group type.",+ "requirePositions": "Whether the group requires members to be positions.",+ "description": "Description of the group type.",+ "membershipType": "Whether members can be in multiple groups or only a single group of this type.",+ "assignmentType": "Whether members are added by manual assignment or by matching a filter expression (or both).",+ "parentTypesAllowed": "Group types allowed for parent groups.",+ "otherGroupTypeId": "If parents can be another group type, the id of that group type.",+ "sourceGroupTypeId": "For a portfolio mirror, the child org group type this type was replicated from.",+ "enableApprovals": "Whether approvals can be used when changing membership.",+ "hidden": "When true, hides groups of this type from the Org Chart Groups view and from profile tags.",+ "defaultSensitivity": "Default sensitivity for groups of this type.",+ "positions": "List of positions (e.g. 'lead') that exist on groups of this type.",+ "membershipFieldId": "Id of the field that indicates membership in groups of this type.",+ "createAt": "Created timestamp.",+ "updateAt": "Last updated timestamp.",+ "deleteAt": "Deleted timestamp.",+ },+ },+ "job_levels": {+ "description": "Job levels configured for the organization's leveling framework.",+ "docs_url": "https://api.charthop.com/swagger#/job-level/findJobLevels",+ "columns": {+ "id": "Globally unique id.",+ "orgId": "Parent organization id.",+ "label": "Human-readable name of the job level.",+ "code": "Job level code.",+ "benchmarkType": "Whether to use Radford or Option Impact as a benchmark.",+ "benchmarkLevel": "Radford or Option Impact level used as a reference.",+ "createAt": "Created timestamp.",+ "updateAt": "Last updated timestamp.",+ "deleteAt": "Deleted timestamp.",+ },+ },+ "job_codes": {+ "description": "Job codes mapping codes to standardized job titles.",+ "docs_url": "https://api.charthop.com/swagger#/job-code/findJobCodes",+ "columns": {+ "id": "Globally unique id.",+ "orgId": "Parent organization id (empty if global).",+ "title": "Job title corresponding to this job code.",+ "code": "Code of the job code.",+ "notes": "Description of the job code.",+ "color": "Hex color string for the job code.",+ "image": "Path to the job code image.",+ "createAt": "Created timestamp.",+ "updateAt": "Last updated timestamp.",+ "deleteAt": "Deleted timestamp.",+ },+ },+ "changes": {+ "description": "Changes across the organization — hires, departures, moves, and field updates including compensation changes.",+ "docs_url": "https://api.charthop.com/swagger#/change/findChanges",+ "columns": {+ "id": "Unique id.",+ "jobId": "Job id.",+ "orgId": "Parent organization id.",+ "scenarioId": "Scenario that this change belongs to.",+ "mergeScenarioId": "Scenario that this change was merged in from, if the change originally came from a scenario.",+ "parentChangeId": "Change that this change emanates from.",+ "priorStateChangeId": "Connects this change to a previous version of itself that can be rolled back to.",+ "type": "Type of change (e.g. HIRE, DEPART, MOVE, UPDATE).",+ "date": "Effective date of the change.",+ "sort": "Sort order of the change.",+ "announceDate": "For HIRE and DEPART changes, the announce date, if different from the date of change.",+ "status": "Whether the change is active or not.",+ "personId": "The id of the person involved, or empty if no person is attached to the job.",+ "otherJobId": "For MOVE changes, the id of the job moved from; for RELATE changes, the id of the other job.",+ "otherPersonId": "For MOVE changes, the id of the other person involved in the move.",+ "departType": "For DEPART changes, the type of departure.",+ "departRegret": "For DEPART changes, whether the departure was regrettable.",+ "promotionType": "Whether the change is a promotion or a demotion.",+ "reason": "The reason for the change.",+ "relateType": "For RELATE changes, the type of the relationship.",+ "job": "For CREATE changes, the initial job data; for other changes, the title and groups at the time of change.",+ "otherJob": "If otherJobId is present, the title and person start date of the other job at the time of change.",+ "formId": "If this change was data submitted by a form, the id of that form.",+ "formResponseId": "If this change is associated with a form response, the id of that form response.",+ "update": "For UPDATE changes, the data being updated.",+ "note": "Note on the change.",+ "createAt": "Created timestamp.",+ "updateAt": "Updated timestamp.",+ "statusAt": "Timestamp of the status change.",+ "approvalAt": "Timestamp of approval.",+ "approvalNote": "Approval or rejection note.",+ },+ },+ "time_off": {+ "description": "Time off requests for people in the organization.",+ "docs_url": "https://api.charthop.com/swagger#/timeoff/findTimeOff",+ "columns": {+ "id": "Globally unique id of the time off.",+ "orgId": "Org that the time off belongs to.",+ "personId": "Person taking the time off.",+ "externalId": "External identifier, if the time off was synced from an external system.",+ "startDate": "Start date of the time off, inclusive.",+ "startDatePartialDay": "Portion of the start date taken.",+ "startDatePartialDayPeriod": "Portion of the start day requested (e.g. AM or PM).",+ "endDate": "End date of the time off, inclusive.",+ "endDatePartialDay": "Portion of the end date taken.",+ "endDatePartialDayPeriod": "Portion of the end day requested (e.g. AM or PM).",+ "days": "Number of days used.",+ "hours": "Number of hours used.",+ "typeDescription": "Type of time off.",+ "timeOffPolicyId": "Policy id the balance is pulled from.",+ "note": "Notes on the time off.",+ "approval": "Approval status of the time off.",+ "approvalAt": "Timestamp of approval.",+ "approvalUserId": "User who is next to approve, or who did the final approval or rejection.",+ "createAt": "Created timestamp.",+ "updateAt": "Updated timestamp.",+ "deleteAt": "Deleted timestamp.",+ "requestAt": "Requested at timestamp, often the same as createAt.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/charthop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/charthop.pynew file mode 100644index 000000000000..b33200b33dc2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/charthop.py@@ -0,0 +1,293 @@+import time+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, 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.charthop.settings import (+ CHARTHOP_ENDPOINTS,+ ChartHopEndpointConfig,+)+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++CHARTHOP_BASE_URL = "https://api.charthop.com"+# No documented max page size; ChartHop's own sync tooling pages with limit=1000. 500 keeps+# the request count low (rate limits are undocumented) while bounding per-page payload size.+PAGE_SIZE = 500+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60++AUTH_ERROR_HINT = "ChartHop API authentication or permission error"+++class ChartHopRetryableError(Exception):+ pass+++class ChartHopAPIError(Exception):+ pass+++class ChartHopResumeConfig:+ # ``next`` token of the last fully-yielded page, re-sent as ``from`` on resume.+ from_token: str+ # The incremental start date the interrupted run was using. Reused verbatim on resume:+ # the watermark may have advanced from committed batches, and pairing the saved ``from``+ # id with a narrower date window would ask the API to paginate from an id outside the+ # filtered result set, which has undefined behavior.+ start_date: Optional[str] = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _to_charthop_date(value: Any) -> Optional[str]:+ """Coerce an incremental cursor value to the YYYY-MM-DD format ChartHop's ``date``+ filter expects, clamped to today. A change's effective date can be in the future+ (scheduled promotions/hires); without the clamp the watermark would start future runs+ past changes entered later for earlier dates."""+ if isinstance(value, datetime):+ value = (value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)).date()+ elif isinstance(value, str):+ try:+ value = date.fromisoformat(value[:10])+ except ValueError:+ return None+ if not isinstance(value, date):+ return None+ today = datetime.now(UTC).date()+ return min(value, today).isoformat()+++def _endpoint_path(config: ChartHopEndpointConfig, org_id: str) -> str:+ # Encode the org id as a single path segment so a crafted value (slashes, query+ # delimiters) can't redirect the request to a different endpoint with the stored token.+ return config.path.format(org_id=quote(org_id, safe=""))+++def _build_url(path: str, params: dict[str, Any]) -> str:+ clean_params = {key: value for key, value in params.items() if value is not None}+ if not clean_params:+ return f"{CHARTHOP_BASE_URL}{path}"+ return f"{CHARTHOP_BASE_URL}{path}?{urlencode(clean_params)}"+++def _build_params(+ config: ChartHopEndpointConfig,+ from_token: Optional[str],+ start_date: Optional[str],+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.extra_params}+ if from_token is not None:+ params["from"] = from_token+ # The ``next`` token is a bare entity id, not a full query, so filters are re-sent on+ # every page — the date window stays applied across the whole pagination walk.+ if config.incremental_param is not None and start_date is not None:+ params[config.incremental_param] = start_date+ return params+++PageFetcher = Callable[[str], dict[str, Any]]+++def _make_page_fetcher(api_key: str, logger: FilteringBoundLogger) -> PageFetcher:+ headers = _get_headers(api_key)+ session = make_tracked_session()++ @retry(+ retry=retry_if_exception_type(+ (+ ChartHopRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(page_url: str) -> dict[str, Any]:+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # ChartHop's rate limits are undocumented; honor Retry-After when present and fall+ # back to tenacity's exponential backoff.+ if response.status_code == 429:+ retry_after = response.headers.get("Retry-After")+ if retry_after is not None:+ try:+ time.sleep(min(int(retry_after), MAX_RETRY_AFTER_SECONDS))+ except ValueError:+ pass+ raise ChartHopRetryableError(f"ChartHop API rate limited: status=429, url={page_url}")++ if response.status_code >= 500:+ raise ChartHopRetryableError(+ f"ChartHop API error (retryable): status={response.status_code}, url={page_url}"+ )++ if response.status_code in (401, 403):+ raise ChartHopAPIError(f"{response.status_code} Client Error: {AUTH_ERROR_HINT} for url {page_url}")++ if not response.ok:+ logger.error(f"ChartHop API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ return fetch_page+++def resolve_org_id(api_key: str, configured_org_id: Optional[str]) -> str:+ """Resolve the org id (or slug) every data endpoint needs in its path.++ Self-serve ChartHop API tokens are generated per org, so ``GET /v1/org`` normally+ returns exactly one org and the field can stay empty. A token that can see several+ orgs must say which one to sync.+ """+ if configured_org_id and configured_org_id.strip():+ return configured_org_id.strip()++ response = make_tracked_session().get(+ _build_url("/v1/org", {"limit": 2}), headers=_get_headers(api_key), timeout=REQUEST_TIMEOUT_SECONDS+ )+ if response.status_code in (401, 403):+ raise ChartHopAPIError(f"{response.status_code} Client Error: {AUTH_ERROR_HINT} for url /v1/org")+ response.raise_for_status()++ orgs = response.json().get("data", [])+ if len(orgs) == 0:+ raise ChartHopAPIError("ChartHop API token has no access to any organization")+ if len(orgs) > 1:+ raise ChartHopAPIError(+ "ChartHop API token can access multiple organizations. Set the organization ID or slug on the source."+ )+ return orgs[0]["id"]+++def check_access(api_key: str, org_id: Optional[str], schema_name: Optional[str]) -> tuple[int, Optional[str]]:+ """Probe the API to validate credentials.++ Returns a normalized ``(status, message)``: 200 = reachable, 401 = bad token,+ 403 = valid token without access, 404 = org not found, 0 = network/unexpected error.+ Validating a specific schema probes that endpoint with ``limit=1`` so tokens scoped+ to a subset of the data fail fast on the schemas they can't read.+ """+ session = make_tracked_session()+ try:+ resolved_org_id = resolve_org_id(api_key, org_id)++ if schema_name is not None:+ config = CHARTHOP_ENDPOINTS[schema_name]+ path = _endpoint_path(config, resolved_org_id)+ response = session.get(+ _build_url(path, {"limit": 1, **config.extra_params}),+ headers=_get_headers(api_key),+ timeout=15,+ )+ return response.status_code, None++ return 200, None+ except ChartHopAPIError as e:+ message = str(e)+ if "401" in message:+ return 401, message+ if "403" in message:+ return 403, message+ return 0, message+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else 0+ return status, str(e)+ except Exception as e:+ return 0, f"Could not connect to ChartHop: {e}"+++def get_rows(+ api_key: str,+ org_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChartHopResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CHARTHOP_ENDPOINTS[endpoint]+ fetch_page = _make_page_fetcher(api_key, logger)+ path = _endpoint_path(config, org_id)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ logger.debug(f"ChartHop: resuming {endpoint} from saved cursor")+ from_token: Optional[str] = resume_config.from_token+ start_date = resume_config.start_date+ else:+ from_token = None+ start_date = (+ _to_charthop_date(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value is not None+ else None+ )++ while True:+ url = _build_url(path, _build_params(config, from_token, start_date))+ data = fetch_page(url)+ rows = data.get("data", []) or []++ if rows:+ yield rows++ from_token = data.get("next")+ if not from_token:+ break++ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the+ # primary key) rather than skipping it.+ resumable_source_manager.save_state(ChartHopResumeConfig(from_token=from_token, start_date=start_date))+++def charthop_source(+ api_key: str,+ org_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChartHopResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CHARTHOP_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ org_id=org_id,+ 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,+ ),+ primary_keys=config.primary_key,+ # The change endpoint documents ascending effective-date order as its default+ # (``desc=false``); every other endpoint is full refresh, where sort mode doesn't+ # gate watermark checkpointing.+ sort_mode="asc",+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/settings.pynew file mode 100644index 000000000000..250cd44b54bf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/settings.py@@ -0,0 +1,82 @@+from dataclasses import dataclass, field+from typing import Any, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class ChartHopEndpointConfig:+ name: str+ """Table name we expose to the user (snake_case)."""+ path: str+ """API path relative to the base URL, with ``{org_id}`` left for the resolved org."""+ primary_key: list[str] = field(default_factory=lambda: ["id"])+ extra_params: dict[str, Any] = field(default_factory=dict)+ """Static query params sent on every request for the endpoint."""+ incremental_param: Optional[str] = None+ """Server-side "start from" query param. Only set where the API genuinely filters."""+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ partition_key: Optional[str] = None+ """A STABLE field to partition on. Never an updated_at-style field, which would+ rewrite partitions on every sync."""+++# Every ChartHop list endpoint paginates the same way: cursor-by-id via ``from=<last id>``+# plus ``limit=<n>``, with the response envelope ``{"data": [...], "next": "<from token>"}``.+#+# Incremental sync is only advertised on ``changes``: /v1/org/{orgId}/change accepts a+# server-side ``date`` (start, inclusive) filter on the change's effective date and returns+# rows in ascending date order by default (``desc=false``). Person, job, and group list+# endpoints support as-of ``date`` snapshots but no updated-since filter, and the time-off+# endpoint's ``fromDate`` filters on the time off's own date range (backdated requests+# entered later would be skipped forever), so all of those are full refresh only.+CHARTHOP_ENDPOINTS: dict[str, ChartHopEndpointConfig] = {+ "persons": ChartHopEndpointConfig(+ name="persons",+ path="/v2/org/{org_id}/person",+ # Include ex-employees so departures stay queryable in the warehouse.+ extra_params={"includeAll": "true"},+ ),+ "jobs": ChartHopEndpointConfig(+ name="jobs",+ path="/v2/org/{org_id}/job",+ ),+ "groups": ChartHopEndpointConfig(+ name="groups",+ path="/v2/org/{org_id}/group",+ ),+ "group_types": ChartHopEndpointConfig(+ name="group_types",+ path="/v1/org/{org_id}/group-type",+ ),+ "job_levels": ChartHopEndpointConfig(+ name="job_levels",+ path="/v1/org/{org_id}/job-level",+ ),+ "job_codes": ChartHopEndpointConfig(+ name="job_codes",+ path="/v1/org/{org_id}/job-code",+ ),+ "changes": ChartHopEndpointConfig(+ name="changes",+ path="/v1/org/{org_id}/change",+ incremental_param="date",+ # A change's effective date is set once and rarely edited, so it doubles as a+ # stable partition key (createAt isn't guaranteed present on older rows).+ partition_key="date",+ incremental_fields=[+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ ),+ "time_off": ChartHopEndpointConfig(+ name="time_off",+ path="/v1/org/{org_id}/timeoff",+ ),+}++ENDPOINTS = tuple(CHARTHOP_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.pyindex 7a4267de2d3e..ce17863ac5be 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.py@@ -1,31 +1,170 @@-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.charthop.charthop import (+ AUTH_ERROR_HINT,+ ChartHopResumeConfig,+ charthop_source,+ check_access,+ resolve_org_id,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.settings import (+ CHARTHOP_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 ChartHopSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ChartHopSource(SimpleSource[ChartHopSourceConfig]):+class ChartHopSource(ResumableSource[ChartHopSourceConfig, ChartHopResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CHARTHOP+ @property+ def connection_host_fields(self) -> list[str]:+ # `org_id` selects which org the stored API token is used against; retargeting it must+ # re-require the token so an editor can't point the preserved credential at another org.+ return ["org_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CHART_HOP,category=DataWarehouseSourceCategory.HR___RECRUITING,label="ChartHop",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your ChartHop API token to pull your ChartHop people, org chart, and compensation-change data into the PostHog Data warehouse.++You can generate an API token in ChartHop under **Settings → API**. The token's access level determines which data the source can read.++The organization ID (or slug) is optional — it's detected automatically when your token can access exactly one organization.+""",+ docsUrl="https://posthog.com/docs/cdp/sources/charthop",iconPath="/static/services/charthop.png",keywords=["hr", "people analytics", "org chart", "compensation"],- fields=cast(list[FieldType], []),unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="org_id",+ label="Organization ID or slug (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ChartHopSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=CHARTHOP_ENDPOINTS[endpoint].incremental_param is not None,+ supports_append=CHARTHOP_ENDPOINTS[endpoint].incremental_param is not None,+ incremental_fields=CHARTHOP_ENDPOINTS[endpoint].incremental_fields,+ )+ 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: ChartHopSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in CHARTHOP_ENDPOINTS:+ return False, f"Unknown ChartHop schema '{schema_name}'"++ status, message = check_access(config.api_key, config.org_id, schema_name)++ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid ChartHop API token"+ if status == 403:+ if schema_name is not None:+ return False, f"Your ChartHop API token does not have permission to read '{schema_name}'"+ return False, message or "Your ChartHop API token does not have access to this organization"+ if status == 404 and config.org_id:+ return False, f"ChartHop organization '{config.org_id}' was not found"++ return False, message or "Could not validate ChartHop credentials"++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your ChartHop API token is invalid or expired. Please generate a new token and reconnect.",+ "403 Client Error": "Your ChartHop API token does not have the required permissions. Please check the token's access level and try again.",+ AUTH_ERROR_HINT: "Your ChartHop API token is invalid or lacks the required permissions. Please check the token and try again.",+ "has no access to any organization": "Your ChartHop API token has no access to any organization. Please generate a new token and reconnect.",+ "can access multiple organizations": "Your ChartHop API token can access multiple organizations. Set the organization ID or slug on the source.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ChartHopResumeConfig]:+ return ResumableSourceManager[ChartHopResumeConfig](inputs, ChartHopResumeConfig)++ def source_for_pipeline(+ self,+ config: ChartHopSourceConfig,+ resumable_source_manager: ResumableSourceManager[ChartHopResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return charthop_source(+ api_key=config.api_key,+ org_id=resolve_org_id(config.api_key, config.org_id),+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop.pynew file mode 100644index 000000000000..01ad743ca23a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop.py@@ -0,0 +1,248 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.charthop import (+ CHARTHOP_BASE_URL,+ PAGE_SIZE,+ ChartHopAPIError,+ ChartHopResumeConfig,+ _to_charthop_date,+ charthop_source,+ get_rows,+ resolve_org_id,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.settings import ENDPOINTS++SESSION_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.charthop.charthop.make_tracked_session"+++class FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None) -> None:+ self.status_code = status_code+ self._json = json_data if json_data is not None else {}+ self.text = str(self._json)+ self.headers: dict[str, str] = {}++ @property+ def ok(self) -> bool:+ return 200 <= self.status_code < 300++ def json(self) -> dict[str, Any]:+ return self._json++ def raise_for_status(self) -> None:+ if not self.ok:+ raise Exception(f"{self.status_code} Client Error")+++class FakeSession:+ def __init__(self, responses: list[FakeResponse]) -> None:+ self._responses = list(responses)+ self.calls: list[str] = []++ def get(self, url: str, headers: Any = None, timeout: Any = None):+ self.calls.append(url)+ return self._responses[0] if len(self._responses) == 1 else self._responses.pop(0)+++def _manager(can_resume: bool = False, state: Optional[ChartHopResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = state+ return manager+++class TestToChartHopDate:+ @parameterized.expand(+ [+ ("date", date(2026, 1, 15), "2026-01-15"),+ ("aware_datetime", datetime(2026, 1, 15, 12, 30, tzinfo=UTC), "2026-01-15"),+ ("naive_datetime", datetime(2026, 1, 15, 12, 30), "2026-01-15"),+ ("date_string", "2026-01-15", "2026-01-15"),+ ("datetime_string", "2026-01-15T12:30:00Z", "2026-01-15"),+ ("garbage_string", "not-a-date", None),+ ("non_date_type", 12345, None),+ ]+ )+ def test_coercion(self, _name: str, value: Any, expected: Optional[str]) -> None:+ assert _to_charthop_date(value) == expected++ def test_future_date_clamped_to_today(self) -> None:+ future = date.today().replace(year=date.today().year + 1)+ assert _to_charthop_date(future) == datetime.now(UTC).date().isoformat()+++class TestGetRows:+ def test_paginates_forwarding_from_token(self) -> None:+ responses = [+ FakeResponse(json_data={"data": [{"id": "1"}], "next": "1"}),+ FakeResponse(json_data={"data": [{"id": "2"}]}),+ ]+ session = FakeSession(responses)+ manager = _manager()++ with mock.patch(SESSION_PATH, return_value=session):+ batches = list(get_rows("key", "org-1", "jobs", mock.MagicMock(), manager))++ assert batches == [[{"id": "1"}], [{"id": "2"}]]+ assert session.calls[0] == f"{CHARTHOP_BASE_URL}/v2/org/org-1/job?limit={PAGE_SIZE}"+ assert session.calls[1] == f"{CHARTHOP_BASE_URL}/v2/org/org-1/job?limit={PAGE_SIZE}&from=1"++ def test_org_id_is_encoded_as_single_path_segment(self) -> None:+ responses = [FakeResponse(json_data={"data": []})]+ session = FakeSession(responses)++ with mock.patch(SESSION_PATH, return_value=session):+ list(get_rows("key", "org/../evil?x=1", "jobs", mock.MagicMock(), _manager()))++ assert session.calls[0].startswith(f"{CHARTHOP_BASE_URL}/v2/org/org%2F..%2Fevil%3Fx%3D1/job?")++ def test_saves_state_after_yielding_each_page(self) -> None:+ responses = [+ FakeResponse(json_data={"data": [{"id": "1"}], "next": "1"}),+ FakeResponse(json_data={"data": [{"id": "2"}]}),+ ]+ manager = _manager()++ with mock.patch(SESSION_PATH, return_value=FakeSession(responses)):+ list(get_rows("key", "org-1", "jobs", mock.MagicMock(), manager))++ manager.save_state.assert_called_once_with(ChartHopResumeConfig(from_token="1", start_date=None))++ def test_resumes_from_saved_cursor_and_start_date(self) -> None:+ responses = [FakeResponse(json_data={"data": [{"id": "9"}]})]+ session = FakeSession(responses)+ manager = _manager(can_resume=True, state=ChartHopResumeConfig(from_token="8", start_date="2026-01-01"))++ with mock.patch(SESSION_PATH, return_value=session):+ batches = list(+ get_rows(+ "key",+ "org-1",+ "changes",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ # The saved window must win over the advanced watermark on resume.+ db_incremental_field_last_value=date(2026, 2, 1),+ )+ )++ assert batches == [[{"id": "9"}]]+ assert "from=8" in session.calls[0]+ assert "date=2026-01-01" in session.calls[0]++ def test_incremental_date_filter_sent_on_every_page(self) -> None:+ responses = [+ FakeResponse(json_data={"data": [{"id": "1"}], "next": "1"}),+ FakeResponse(json_data={"data": [{"id": "2"}]}),+ ]+ session = FakeSession(responses)++ with mock.patch(SESSION_PATH, return_value=session):+ list(+ get_rows(+ "key",+ "org-1",+ "changes",+ mock.MagicMock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 15),+ )+ )++ assert all("date=2026-01-15" in url for url in session.calls)++ def test_full_refresh_endpoint_never_sends_date_filter(self) -> None:+ responses = [FakeResponse(json_data={"data": [{"id": "1"}]})]+ session = FakeSession(responses)++ with mock.patch(SESSION_PATH, return_value=session):+ list(+ get_rows(+ "key",+ "org-1",+ "jobs",+ mock.MagicMock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 15),+ )+ )++ assert "date=" not in session.calls[0]++ def test_persons_includes_ex_employees(self) -> None:+ responses = [FakeResponse(json_data={"data": []})]+ session = FakeSession(responses)++ with mock.patch(SESSION_PATH, return_value=session):+ batches = list(get_rows("key", "org-1", "persons", mock.MagicMock(), _manager()))++ assert batches == []+ assert "includeAll=true" in session.calls[0]++ @parameterized.expand([(401,), (403,)])+ def test_http_auth_errors_raise_matchable_api_error(self, status_code: int) -> None:+ with mock.patch(SESSION_PATH, return_value=FakeSession([FakeResponse(status_code=status_code)])):+ with pytest.raises(ChartHopAPIError) as exc:+ list(get_rows("key", "org-1", "jobs", mock.MagicMock(), _manager()))+ assert f"{status_code} Client Error" in str(exc.value)+++class TestResolveOrgId:+ @parameterized.expand([("plain", "org-1"), ("padded", " org-1 ")])+ def test_configured_org_id_skips_lookup(self, _name: str, configured: str) -> None:+ session = mock.MagicMock()+ with mock.patch(SESSION_PATH, return_value=session):+ assert resolve_org_id("key", configured) == "org-1"+ session.get.assert_not_called()++ def test_single_org_auto_detected(self) -> None:+ response = FakeResponse(json_data={"data": [{"id": "org-9"}]})+ with mock.patch(SESSION_PATH, return_value=FakeSession([response])):+ assert resolve_org_id("key", None) == "org-9"++ @parameterized.expand(+ [+ ("no_orgs", [], "has no access to any organization"),+ ("multiple_orgs", [{"id": "a"}, {"id": "b"}], "can access multiple organizations"),+ ]+ )+ def test_zero_or_multiple_orgs_raise(self, _name: str, orgs: list[dict[str, Any]], expected_message: str) -> None:+ response = FakeResponse(json_data={"data": orgs})+ with mock.patch(SESSION_PATH, return_value=FakeSession([response])):+ with pytest.raises(ChartHopAPIError) as exc:+ resolve_org_id("key", "")+ assert expected_message in str(exc.value)++ def test_auth_error_raises_matchable_api_error(self) -> None:+ with mock.patch(SESSION_PATH, return_value=FakeSession([FakeResponse(status_code=401)])):+ with pytest.raises(ChartHopAPIError) as exc:+ resolve_org_id("key", None)+ assert "401 Client Error" in str(exc.value)+++class TestChartHopSource:+ def test_changes_partitioned_by_effective_date(self) -> None:+ response = charthop_source("key", "org-1", "changes", mock.MagicMock(), _manager())+ assert response.name == "changes"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date"]++ def test_full_refresh_endpoint_is_unpartitioned(self) -> None:+ response = charthop_source("key", "org-1", "persons", mock.MagicMock(), _manager())+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_all_endpoints_buildable(self) -> None:+ for endpoint in ENDPOINTS:+ response = charthop_source("key", "org-1", endpoint, mock.MagicMock(), _manager())+ assert response.primary_keys == ["id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop_source.pynew file mode 100644index 000000000000..8396ce8211b5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop_source.py@@ -0,0 +1,163 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.charthop import ChartHopResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.source import ChartHopSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChartHopSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++CHECK_ACCESS_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.charthop.source.check_access"+++class TestChartHopSource:+ def setup_method(self) -> None:+ self.source = ChartHopSource()+ self.team_id = 123+ self.config = ChartHopSourceConfig(api_key="charthop-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CHARTHOP++ def test_org_id_is_a_connection_host_field(self) -> None:+ # Changing org_id must force the api_key to be re-entered, so the stored token is+ # never retargeted at another org the editor doesn't hold credentials for.+ assert self.source.connection_host_fields == ["org_id"]++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "ChartHop"+ assert config.label == "ChartHop"+ assert config.releaseStatus == ReleaseStatus.ALPHA++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "org_id"]++ def test_api_key_field_is_secret_password_and_org_id_optional(self) -> None:+ config = self.source.get_source_config+ api_key = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.secret is True+ assert api_key.required is True++ org_id = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "org_id")+ assert org_id.required is False+ assert org_id.secret is False++ def test_get_schemas_only_changes_is_incremental(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ by_name = {s.name: s for s in schemas}+ assert by_name["changes"].supports_incremental is True+ assert [f["field"] for f in by_name["changes"].incremental_fields] == ["date"]+ for name, schema in by_name.items():+ if name != "changes":+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["persons", "nope"])+ assert [s.name for s in schemas] == ["persons"]++ @parameterized.expand(+ [+ ("bad_token", "401 Client Error: ChartHop API authentication or permission error for url /v1/org"),+ ("no_permission", "403 Client Error: ChartHop API authentication or permission error for url x"),+ ("no_org_access", "ChartHop API token has no access to any organization"),+ (+ "multiple_orgs",+ "ChartHop API token can access multiple organizations. Set the organization ID or slug on the source.",+ ),+ ]+ )+ def test_non_retryable_errors_match_credential_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("server_error", "ChartHop API error (retryable): status=503, url=x"),+ ("rate_limited", "ChartHop API rate limited: status=429, url=x"),+ ]+ )+ def test_non_retryable_errors_ignore_transient_failures(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @parameterized.expand(+ [+ ("ok", 200, None, True, None),+ ("bad_token", 401, None, False, "Invalid ChartHop API token"),+ (+ "schema_forbidden",+ 403,+ "persons",+ False,+ "Your ChartHop API token does not have permission to read 'persons'",+ ),+ ("org_forbidden", 403, None, False, "boom"),+ ("network_error", 0, None, False, "boom"),+ ]+ )+ @mock.patch(CHECK_ACCESS_PATH)+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ schema_name: str | None,+ expected_valid: bool,+ expected_message: str | None,+ mock_check: mock.MagicMock,+ ) -> None:+ mock_check.return_value = (status, "boom")+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)+ assert is_valid is expected_valid+ assert message == expected_message++ @mock.patch(CHECK_ACCESS_PATH)+ def test_validate_credentials_org_not_found(self, mock_check: mock.MagicMock) -> None:+ mock_check.return_value = (404, None)+ config = ChartHopSourceConfig(api_key="charthop-token", org_id="typo-org")+ is_valid, message = self.source.validate_credentials(config, self.team_id)+ assert is_valid is False+ assert message == "ChartHop organization 'typo-org' was not found"++ @mock.patch(CHECK_ACCESS_PATH)+ def test_validate_credentials_rejects_unknown_schema_without_probing(self, mock_check: mock.MagicMock) -> None:+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")+ assert is_valid is False+ assert message == "Unknown ChartHop schema 'not_a_table'"+ mock_check.assert_not_called()++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ChartHopResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.charthop.source.resolve_org_id")+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.charthop.source.charthop_source")+ def test_source_for_pipeline_plumbs_arguments(+ self, mock_charthop_source: mock.MagicMock, mock_resolve: mock.MagicMock+ ) -> None:+ mock_resolve.return_value = "org-42"+ inputs = mock.MagicMock()+ inputs.schema_name = "changes"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_resolve.assert_called_once_with("charthop-token", None)+ kwargs = mock_charthop_source.call_args.kwargs+ assert kwargs["api_key"] == "charthop-token"+ assert kwargs["org_id"] == "org-42"+ assert kwargs["endpoint"] == "changes"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"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 bc6c78ec1f3e..4628d6f43336 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@@ -687,7 +687,8 @@ class ChargifySourceConfig(config.Config):@config.configclass ChartHopSourceConfig(config.Config):- pass+ api_key: str+ org_id: str | None = None@config.config