: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 fulcrum import source (#67839)
Tom Owers82fe1b1a0c70
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 269caae187e0..cb89d49c6d91 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -154,6 +154,7 @@ the row lists both.| fleetio | HTTP | requests | ✅ || firehydrant | HTTP | requests | ✅ || front | HTTP | requests | ✅ |+| fulcrum | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || giphy | HTTP | requests | ✅ |@@ -445,6 +446,7 @@ doesn't conflict with concurrent PRs.- freshbooks- freshcaller- freshchat+- freshservice- fulcrum- gainsight_px- gitbookdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/canonical_descriptions.pynew file mode 100644index 000000000000..2f5680670a18--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/canonical_descriptions.py@@ -0,0 +1,160 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Fulcrum (Spatial Networks) REST API v2 docs+# (https://docs.fulcrumapp.com/reference). Partial coverage is fine — anything not described+# here falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "records": {+ "description": "Individual data-collection entries captured against a form, including their geospatial location and per-form field values.",+ "docs_url": "https://docs.fulcrumapp.com/reference/records-intro",+ "columns": {+ "id": "Unique identifier for the record.",+ "form_id": "Identifier of the form this record belongs to.",+ "created_at": "Timestamp when the record was synced to the cloud.",+ "updated_at": "Timestamp when the record was last synced to or processed in the cloud.",+ "latitude": "Record location latitude in WGS 84 decimal degrees.",+ "longitude": "Record location longitude in WGS 84 decimal degrees.",+ "form_values": "Object of the record's field values, keyed by the form schema's element keys.",+ "status": "The record's status value, which sets the color of its map marker.",+ "project_id": "Identifier of the project this record is assigned to, if any.",+ "assigned_to_id": "Identifier of the member this record is assigned to, if any.",+ },+ },+ "forms": {+ "description": "Form definitions (the schema of a data-collection app), including their custom elements.",+ "docs_url": "https://docs.fulcrumapp.com/reference/forms-intro",+ "columns": {+ "id": "Unique identifier for the form.",+ "name": "The name given to this form.",+ "description": "The description given to this form.",+ "created_at": "Timestamp when the form was created.",+ "updated_at": "Timestamp when the form was last updated.",+ "elements": "The form's custom elements (its field schema).",+ "status_field": "The form's status field configuration.",+ "record_count": "The number of records in this form.",+ },+ },+ "choice_lists": {+ "description": "Reusable lists of choices that can be referenced by choice fields across forms.",+ "docs_url": "https://docs.fulcrumapp.com/reference/choice-lists-intro",+ "columns": {+ "id": "Unique identifier for the choice list.",+ "name": "The name of the choice list.",+ "created_at": "Timestamp when the choice list was created.",+ "updated_at": "Timestamp when the choice list was last updated.",+ },+ },+ "classification_sets": {+ "description": "Hierarchical classification taxonomies referenced by classification fields on forms.",+ "docs_url": "https://docs.fulcrumapp.com/reference/classification-sets-intro",+ "columns": {+ "id": "Unique identifier for the classification set.",+ "name": "The name of the classification set.",+ "created_at": "Timestamp when the classification set was created.",+ "updated_at": "Timestamp when the classification set was last updated.",+ },+ },+ "projects": {+ "description": "Projects used to group and organize records.",+ "docs_url": "https://docs.fulcrumapp.com/reference/projects-intro",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "The name of the project.",+ "description": "The description of the project.",+ "created_at": "Timestamp when the project was created.",+ "updated_at": "Timestamp when the project was last updated.",+ },+ },+ "memberships": {+ "description": "Members of the organization and their role assignments.",+ "docs_url": "https://docs.fulcrumapp.com/reference/memberships-intro",+ "columns": {+ "id": "Unique identifier for the membership.",+ "name": "The member's name.",+ "email": "The member's email address.",+ "role_id": "Identifier of the role assigned to the member.",+ "created_at": "Timestamp when the membership was created.",+ "updated_at": "Timestamp when the membership was last updated.",+ },+ },+ "roles": {+ "description": "Roles that define the permissions granted to organization members.",+ "docs_url": "https://docs.fulcrumapp.com/reference/roles-get-all",+ "columns": {+ "id": "Unique identifier for the role.",+ "name": "The name of the role.",+ "is_default": "Whether this is the default role for new members.",+ },+ },+ "changesets": {+ "description": "Groups of record changes captured together, used to track edits over time.",+ "docs_url": "https://docs.fulcrumapp.com/reference/changesets-intro",+ "columns": {+ "id": "Unique identifier for the changeset.",+ "form_id": "Identifier of the form the changeset applies to.",+ "created_at": "Timestamp when the changeset was created.",+ "updated_at": "Timestamp when the changeset was last updated.",+ "closed_at": "Timestamp when the changeset was closed, if closed.",+ "number_of_changes": "The count of record changes in this changeset.",+ },+ },+ "webhooks": {+ "description": "Registered webhook endpoints that receive record, form, and other change events.",+ "docs_url": "https://docs.fulcrumapp.com/reference/webhooks-intro",+ "columns": {+ "id": "Unique identifier for the webhook.",+ "url": "The destination URL that receives webhook events.",+ "active": "Whether the webhook is currently enabled.",+ "created_at": "Timestamp when the webhook was created.",+ "updated_at": "Timestamp when the webhook was last updated.",+ },+ },+ "photos": {+ "description": "Metadata for photos captured against records (the binary files are fetched separately).",+ "docs_url": "https://docs.fulcrumapp.com/reference/photos-intro",+ "columns": {+ "access_key": "Unique identifier for the photo.",+ "record_id": "Identifier of the record this photo belongs to.",+ "form_id": "Identifier of the form the record belongs to.",+ "created_at": "Timestamp when the photo was created.",+ "updated_at": "Timestamp when the photo was last updated.",+ "latitude": "Photo capture latitude in WGS 84 decimal degrees.",+ "longitude": "Photo capture longitude in WGS 84 decimal degrees.",+ },+ },+ "signatures": {+ "description": "Metadata for signatures captured against records (the binary files are fetched separately).",+ "docs_url": "https://docs.fulcrumapp.com/reference/signatures-intro",+ "columns": {+ "access_key": "Unique identifier for the signature.",+ "record_id": "Identifier of the record this signature belongs to.",+ "form_id": "Identifier of the form the record belongs to.",+ "created_at": "Timestamp when the signature was created.",+ "updated_at": "Timestamp when the signature was last updated.",+ },+ },+ "videos": {+ "description": "Metadata for videos captured against records (the binary files are fetched separately).",+ "docs_url": "https://docs.fulcrumapp.com/reference/videos-intro",+ "columns": {+ "access_key": "Unique identifier for the video.",+ "record_id": "Identifier of the record this video belongs to.",+ "form_id": "Identifier of the form the record belongs to.",+ "created_at": "Timestamp when the video was created.",+ "updated_at": "Timestamp when the video was last updated.",+ },+ },+ "audio": {+ "description": "Metadata for audio clips captured against records (the binary files are fetched separately).",+ "docs_url": "https://docs.fulcrumapp.com/reference/audio-intro",+ "columns": {+ "access_key": "Unique identifier for the audio resource.",+ "record_id": "Identifier of the record this audio belongs to.",+ "form_id": "Identifier of the form the record belongs to.",+ "created_at": "Timestamp when the audio was created.",+ "updated_at": "Timestamp when the audio was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/fulcrum.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/fulcrum.pynew file mode 100644index 000000000000..e5d82d04f4fe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/fulcrum.py@@ -0,0 +1,201 @@+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.typings import SourceResponse+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+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.settings import (+ FULCRUM_ENDPOINTS,+ FulcrumEndpointConfig,+)++FULCRUM_BASE_URL = "https://api.fulcrumapp.com/api/v2"+++class FulcrumRetryableError(Exception):+ pass+++class FulcrumResumeConfig:+ # Next page number to fetch. Page-number pagination is deterministic and the incremental+ # `updated_since` filter is fixed for the job, so the page number alone is enough to resume.+ page: int+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "X-ApiToken": api_token,+ "Accept": "application/json",+ }+++def _to_epoch_seconds(value: Any) -> Optional[int]:+ """Fulcrum's `updated_since` filter wants the cutoff as integer seconds since epoch."""+ if value is None:+ return None+ if isinstance(value, datetime):+ return int(value.timestamp())+ if isinstance(value, date):+ return int(datetime(value.year, value.month, value.day, tzinfo=UTC).timestamp())+ if isinstance(value, (int, float)):+ return int(value)+ try:+ # ISO 8601 string fallback (e.g. a serialized watermark).+ return int(datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp())+ except (ValueError, TypeError):+ return None+++def _build_params(+ config: FulcrumEndpointConfig,+ page: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"page": page, "per_page": config.page_size}++ if config.supports_incremental and should_use_incremental_field:+ since = _to_epoch_seconds(db_incremental_field_last_value)+ if since is not None:+ # Server-side filter on updated_at. Records default to updated_at ascending order,+ # which matches SourceResponse.sort_mode="asc" so the watermark advances correctly.+ params["updated_since"] = since++ return params+++def _build_url(config: FulcrumEndpointConfig, params: dict[str, Any]) -> str:+ return f"{FULCRUM_BASE_URL}{config.path}?{urlencode(params)}"+++def validate_credentials(api_token: str) -> bool:+ # A cheap, always-available probe: list a single form. 200 means the token is genuine.+ url = _build_url(FULCRUM_ENDPOINTS["forms"], {"page": 1, "per_page": 1})+ try:+ response = make_tracked_session(redact_values=(api_token,)).get(+ url, headers=_get_headers(api_token), timeout=10+ )+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type(+ (+ FulcrumRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ 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 (Fulcrum enforces an hourly request cap) and transient 5xx are retryable.+ if response.status_code == 429 or response.status_code >= 500:+ raise FulcrumRetryableError(f"Fulcrum API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Don't log the raw body on auth failures — keep it out of job logs in case the API echoes+ # anything sensitive. The url holds only the path and pagination params (the token lives in+ # the X-ApiToken header, never the URL).+ if response.status_code in (401, 403):+ logger.error(f"Fulcrum auth error: status={response.status_code}, url={url}")+ else:+ logger.error(f"Fulcrum API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ return response.json()+++def _has_more_pages(data: dict[str, Any], items: list[Any], current_page: int, per_page: int) -> bool:+ """Fulcrum returns current_page/total_pages at the response root; fall back to a short-page+ heuristic if either is missing so we never loop forever or stop early."""+ total_pages = data.get("total_pages")+ if isinstance(total_pages, int):+ page = data.get("current_page")+ page = page if isinstance(page, int) else current_page+ return page < total_pages+ return len(items) >= per_page+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FulcrumResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = FULCRUM_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ session = make_tracked_session(redact_values=(api_token,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None else 1++ while True:+ params = _build_params(config, page, should_use_incremental_field, db_incremental_field_last_value)+ url = _build_url(config, params)+ data = _fetch_page(session, url, headers, logger)++ items = data.get(config.data_key) or []+ if not items:+ break++ yield items++ if not _has_more_pages(data, items, page, config.page_size):+ break++ page += 1+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge+ # dedupes on the primary key.+ resumable_source_manager.save_state(FulcrumResumeConfig(page=page))+++def fulcrum_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FulcrumResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = FULCRUM_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ 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_keys,+ # Records list defaults to updated_at ascending; full-refresh endpoints don't checkpoint a+ # watermark, so ascending is a safe default for them too.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" 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/fulcrum/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/settings.pynew file mode 100644index 000000000000..31a595278ee5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/settings.py@@ -0,0 +1,128 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class FulcrumEndpointConfig:+ name: str+ path: str # e.g. "/records.json"+ data_key: str # response wrapper key holding the array (e.g. "records")+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_key: Optional[str] = None # stable creation-time field for datetime partitioning+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Server-side `updated_since`-style time filter. Only records exposes one; everything+ # else is full-refresh only.+ supports_incremental: bool = False+ page_size: int = 1000 # Fulcrum caps per_page at 20000; keep pages small to bound memory+ should_sync_default: bool = True+++def _updated_at_field() -> list[IncrementalField]:+ return [+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+++FULCRUM_ENDPOINTS: dict[str, FulcrumEndpointConfig] = {+ # Records are the primary, high-volume stream. The list endpoint defaults to ordering by+ # updated_at ascending and exposes a genuine server-side `updated_since` filter (epoch+ # seconds), so it syncs incrementally on updated_at. Partition on created_at (stable).+ "records": FulcrumEndpointConfig(+ name="records",+ path="/records.json",+ data_key="records",+ partition_key="created_at",+ incremental_fields=_updated_at_field(),+ supports_incremental=True,+ ),+ # The resources below have no documented server-side time filter, so they're full refresh.+ "forms": FulcrumEndpointConfig(+ name="forms",+ path="/forms.json",+ data_key="forms",+ partition_key="created_at",+ ),+ "choice_lists": FulcrumEndpointConfig(+ name="choice_lists",+ path="/choice_lists.json",+ data_key="choice_lists",+ partition_key="created_at",+ ),+ "classification_sets": FulcrumEndpointConfig(+ name="classification_sets",+ path="/classification_sets.json",+ data_key="classification_sets",+ partition_key="created_at",+ ),+ "projects": FulcrumEndpointConfig(+ name="projects",+ path="/projects.json",+ data_key="projects",+ partition_key="created_at",+ ),+ "memberships": FulcrumEndpointConfig(+ name="memberships",+ path="/memberships.json",+ data_key="memberships",+ partition_key="created_at",+ ),+ "roles": FulcrumEndpointConfig(+ name="roles",+ path="/roles.json",+ data_key="roles",+ ),+ "changesets": FulcrumEndpointConfig(+ name="changesets",+ path="/changesets.json",+ data_key="changesets",+ partition_key="created_at",+ ),+ "webhooks": FulcrumEndpointConfig(+ name="webhooks",+ path="/webhooks.json",+ data_key="webhooks",+ partition_key="created_at",+ ),+ # Media metadata list endpoints. The identifier is `access_key` (a UUID), not `id`.+ "photos": FulcrumEndpointConfig(+ name="photos",+ path="/photos.json",+ data_key="photos",+ primary_keys=["access_key"],+ partition_key="created_at",+ ),+ "signatures": FulcrumEndpointConfig(+ name="signatures",+ path="/signatures.json",+ data_key="signatures",+ primary_keys=["access_key"],+ partition_key="created_at",+ ),+ "videos": FulcrumEndpointConfig(+ name="videos",+ path="/videos.json",+ data_key="videos",+ primary_keys=["access_key"],+ partition_key="created_at",+ ),+ "audio": FulcrumEndpointConfig(+ name="audio",+ path="/audio.json",+ data_key="audio", # note: singular wrapper key, not "audios"+ primary_keys=["access_key"],+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(FULCRUM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FULCRUM_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/source.pyindex 4b3359f006b7..a3dc221ed895 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/source.py@@ -1,19 +1,43 @@-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.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.fulcrum import (+ FulcrumResumeConfig,+ fulcrum_source,+ validate_credentials as validate_fulcrum_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.settings import (+ ENDPOINTS,+ FULCRUM_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FulcrumSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FulcrumSource(SimpleSource[FulcrumSourceConfig]):+class FulcrumSource(ResumableSource[FulcrumSourceConfig, FulcrumResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FULCRUM@@ -24,7 +48,92 @@ class FulcrumSource(SimpleSource[FulcrumSourceConfig]):name=SchemaExternalDataSourceType.FULCRUM,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Fulcrum",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Fulcrum API token to sync your Fulcrum (Spatial Networks) field data into the PostHog Data warehouse.++You can create an API token in your [Fulcrum account settings](https://web.fulcrumapp.com/settings/api). API access requires the paid Developer Pack subscription, and each token is scoped to a single organization.""",iconPath="/static/services/fulcrum.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/fulcrum",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or unauthorized token surfaces as an HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can't fix a credential problem, so fail the sync. Match+ # the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.fulcrumapp.com": "Your Fulcrum API token is invalid or has been revoked. Create a new token in your Fulcrum account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.fulcrumapp.com": "Your Fulcrum API token does not have access to this data. Confirm the token's organization has an active Developer Pack subscription, then reconnect.",+ }++ def get_schemas(+ self,+ config: FulcrumSourceConfig,+ 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 = FULCRUM_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: FulcrumSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_fulcrum_credentials(config.api_token):+ return True, None++ return False, "Invalid Fulcrum API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FulcrumResumeConfig]:+ return ResumableSourceManager[FulcrumResumeConfig](inputs, FulcrumResumeConfig)++ def source_for_pipeline(+ self,+ config: FulcrumSourceConfig,+ resumable_source_manager: ResumableSourceManager[FulcrumResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return fulcrum_source(+ api_token=config.api_token,+ 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/fulcrum/tests/test_fulcrum.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/tests/test_fulcrum.pynew file mode 100644index 000000000000..01c8dc003ba6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/tests/test_fulcrum.py@@ -0,0 +1,231 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum import fulcrum+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.fulcrum import (+ FulcrumResumeConfig,+ _build_params,+ _has_more_pages,+ _to_epoch_seconds,+ fulcrum_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.settings import FULCRUM_ENDPOINTS+++class TestToEpochSeconds:+ @parameterized.expand(+ [+ ("datetime", datetime(2021, 1, 1, tzinfo=UTC), 1609459200),+ ("date", date(2021, 1, 1), 1609459200),+ ("int_passthrough", 1609459200, 1609459200),+ ("iso_string", "2021-01-01T00:00:00+00:00", 1609459200),+ ("iso_string_z", "2021-01-01T00:00:00Z", 1609459200),+ ("none", None, None),+ ("garbage_string", "not-a-date", None),+ ]+ )+ def test_to_epoch_seconds(self, _name: str, value: Any, expected: int | None) -> None:+ assert _to_epoch_seconds(value) == expected+++class TestBuildParams:+ def test_records_incremental_adds_updated_since(self) -> None:+ params = _build_params(+ FULCRUM_ENDPOINTS["records"],+ page=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC),+ )+ assert params["updated_since"] == 1609459200+ assert params["page"] == 1+ assert params["per_page"] == FULCRUM_ENDPOINTS["records"].page_size++ def test_records_full_refresh_omits_filter(self) -> None:+ params = _build_params(+ FULCRUM_ENDPOINTS["records"],+ page=2,+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC),+ )+ assert "updated_since" not in params+ assert params["page"] == 2++ @parameterized.expand(["forms", "projects", "photos"])+ def test_non_incremental_endpoints_never_filter(self, endpoint: str) -> None:+ # A full-refresh endpoint must never send updated_since even when a watermark is present —+ # the API would silently ignore it, but we keep the request honest.+ params = _build_params(+ FULCRUM_ENDPOINTS[endpoint],+ page=1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC),+ )+ assert "updated_since" not in params+++class TestHasMorePages:+ @parameterized.expand(+ [+ # (total_pages, current_page, items_len, per_page, expected_more)+ ("more_by_total_pages", 3, 1, 1000, 1000, True),+ ("last_by_total_pages", 3, 3, 200, 1000, False),+ ("missing_total_full_page_means_more", None, 1, 1000, 1000, True),+ ("missing_total_short_page_means_done", None, 1, 42, 1000, False),+ ]+ )+ def test_has_more_pages(+ self,+ _name: str,+ total_pages: int | None,+ current_page: int,+ items_len: int,+ per_page: int,+ expected_more: bool,+ ) -> None:+ data: dict[str, Any] = {"current_page": current_page}+ if total_pages is not None:+ data["total_pages"] = total_pages+ items: list[dict[str, Any]] = [{}] * items_len+ assert _has_more_pages(data, items, current_page, per_page) is expected_more+++class TestGetRows:+ def _page(self, data_key: str, items: list[dict], total_pages: int, current_page: int) -> dict[str, Any]:+ return {data_key: items, "total_pages": total_pages, "current_page": current_page}++ def test_paginates_and_yields_each_page(self) -> None:+ manager = mock.Mock()+ manager.can_resume.return_value = False+ pages = [+ self._page("forms", [{"id": "1"}], total_pages=2, current_page=1),+ self._page("forms", [{"id": "2"}], total_pages=2, current_page=2),+ ]+ with mock.patch.object(fulcrum, "_fetch_page", side_effect=pages):+ batches = list(get_rows("token", "forms", mock.Mock(), manager))++ assert batches == [[{"id": "1"}], [{"id": "2"}]]++ def test_stops_on_empty_page(self) -> None:+ manager = mock.Mock()+ manager.can_resume.return_value = False+ with mock.patch.object(fulcrum, "_fetch_page", return_value=self._page("forms", [], 1, 1)):+ batches = list(get_rows("token", "forms", mock.Mock(), manager))+ assert batches == []++ def test_saves_resume_state_after_yielding_each_page(self) -> None:+ # State must be saved AFTER a page is yielded (so a crash re-yields, not skips) and only+ # while more pages remain — the last page saves nothing.+ manager = mock.Mock()+ manager.can_resume.return_value = False+ emitted: list[Any] = []+ pages = [+ self._page("forms", [{"id": "1"}], total_pages=2, current_page=1),+ self._page("forms", [{"id": "2"}], total_pages=2, current_page=2),+ ]++ def _record_save(state: FulcrumResumeConfig) -> None:+ # Capture how many batches had been produced when the save happened.+ emitted.append(("save", state.page, len(batches)))++ manager.save_state.side_effect = _record_save+ with mock.patch.object(fulcrum, "_fetch_page", side_effect=pages):+ batches: list[Any] = []+ for batch in get_rows("token", "forms", mock.Mock(), manager):+ batches.append(batch)++ # One save (advancing to page 2), recorded after the first page was already yielded.+ assert emitted == [("save", 2, 1)]++ def test_resumes_from_saved_page(self) -> None:+ manager = mock.Mock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = FulcrumResumeConfig(page=2)+ seen_urls: list[str] = []++ def _fetch(_session: Any, url: str, _headers: Any, _logger: Any) -> dict[str, Any]:+ seen_urls.append(url)+ return self._page("forms", [{"id": "2"}], total_pages=2, current_page=2)++ with mock.patch.object(fulcrum, "_fetch_page", side_effect=_fetch):+ list(get_rows("token", "forms", mock.Mock(), manager))++ assert "page=2" in seen_urls[0]+++class TestFulcrumSource:+ @parameterized.expand(+ [+ ("records", ["id"], "created_at", "asc"),+ ("photos", ["access_key"], "created_at", "asc"),+ ("roles", ["id"], None, "asc"),+ ]+ )+ def test_source_response_shape(+ self, endpoint: str, expected_pk: list[str], partition_key: str | None, sort_mode: str+ ) -> None:+ response = fulcrum_source("token", endpoint, mock.Mock(), mock.Mock())+ assert response.name == endpoint+ assert response.primary_keys == expected_pk+ assert response.sort_mode == sort_mode+ if partition_key is None:+ assert response.partition_mode is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:+ session = mock.Mock()+ response = mock.Mock(spec=requests.Response)+ response.status_code = status_code+ session.get.return_value = response+ with mock.patch.object(fulcrum, "make_tracked_session", return_value=session):+ assert validate_credentials("token") is expected++ def test_network_error_is_false(self) -> None:+ session = mock.Mock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch.object(fulcrum, "make_tracked_session", return_value=session):+ assert validate_credentials("token") is False+++class TestFetchPage:+ # tenacity exposes the undecorated body as __wrapped__; use it so a single attempt's+ # classification can be asserted without the retry loop actually sleeping.+ _fetch_page_body = staticmethod(fulcrum._fetch_page.__wrapped__) # type: ignore[attr-defined]++ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_status_raises_retryable_error(self, _name: str, status_code: int) -> None:+ # Fulcrum enforces an hourly request cap (429) and can 5xx transiently; both must be+ # classified retryable so a rate limit doesn't hard-fail the whole sync.+ session = mock.Mock()+ response = mock.Mock(spec=requests.Response)+ response.status_code = status_code+ response.ok = False+ response.text = ""+ session.get.return_value = response++ with pytest.raises(fulcrum.FulcrumRetryableError):+ self._fetch_page_body(session, "https://api.fulcrumapp.com/api/v2/forms.json", {}, mock.Mock())++ def test_client_error_raises_for_status(self) -> None:+ session = mock.Mock()+ response = mock.Mock(spec=requests.Response)+ response.status_code = 401+ response.ok = False+ response.text = "unauthorized"+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ self._fetch_page_body(session, "https://api.fulcrumapp.com/api/v2/forms.json", {}, mock.Mock())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/tests/test_fulcrum_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/tests/test_fulcrum_source.pynew file mode 100644index 000000000000..223e18d55395--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fulcrum/tests/test_fulcrum_source.py@@ -0,0 +1,113 @@+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.fulcrum import FulcrumResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.fulcrum.source import FulcrumSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FulcrumSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestFulcrumSourceClass:+ def setup_method(self) -> None:+ self.source = FulcrumSource()+ self.config = FulcrumSourceConfig(api_token="token")+ self.team_id = 1++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FULCRUM++ def test_source_config_has_password_token_field(self) -> None:+ config = self.source.get_source_config+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/fulcrum"+ fields = config.fields or []+ assert len(fields) == 1+ assert fields[0].name == "api_token"+ assert fields[0].type == "password"++ @parameterized.expand([("401 Client Error",), ("403 Client Error",)])+ def test_non_retryable_errors(self, expected_key_prefix: str) -> None:+ keys = self.source.get_non_retryable_errors()+ assert any(k.startswith(expected_key_prefix) for k in keys)++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_records_is_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["records"].supports_incremental is True+ assert [f["field"] for f in schemas["records"].incremental_fields] == ["updated_at"]+ for name, schema in schemas.items():+ if name != "records":+ assert schema.supports_incremental is False, name++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["records", "forms"])+ assert {s.name for s in schemas} == {"records", "forms"}++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials must expose the static catalog for public docs, with the+ # curated record description flowing through.+ assert self.source.lists_tables_without_credentials is True+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert tables["records"]["description"]+ assert tables["photos"]["primary_keys"] == [] # detected keys only populated at sync time++ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Fulcrum API token"))])+ def test_validate_credentials(self, _name: str, api_result: bool, expected: tuple[bool, str | None]) -> None:+ with mock.patch.object(source_module, "validate_fulcrum_credentials", return_value=api_result):+ assert self.source.validate_credentials(self.config, self.team_id) == expected++ def test_get_resumable_source_manager_bound_to_data_class(self) -> None:+ inputs = mock.Mock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FulcrumResumeConfig++ def test_source_for_pipeline_plumbs_incremental_args(self) -> None:+ inputs = mock.Mock()+ inputs.schema_name = "records"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2021-01-01"+ manager = mock.Mock()++ with mock.patch.object(source_module, "fulcrum_source") as mocked:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mocked.call_args.kwargs+ assert kwargs["api_token"] == "token"+ assert kwargs["endpoint"] == "records"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2021-01-01"++ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:+ inputs = mock.Mock()+ inputs.schema_name = "forms"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2021-01-01"+ manager = mock.Mock()++ with mock.patch.object(source_module, "fulcrum_source") as mocked:+ self.source.source_for_pipeline(self.config, manager, inputs)++ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestCanonicalDescriptions:+ def test_keys_are_all_real_endpoints(self) -> None:+ # A canonical entry keyed by a name that isn't an endpoint would silently never render.+ descriptions: dict[str, Any] = FulcrumSource().get_canonical_descriptions()+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "records" in descriptions+++if __name__ == "__main__":+ pytest.main([__file__])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 59f4cd8f9c85..7386bcd5ecc3 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@@ -1285,7 +1285,7 @@ class FrontSourceConfig(config.Config):@config.configclass FulcrumSourceConfig(config.Config):- pass+ api_token: str@config.config