: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 featurebase import source (#71224)
Tom Owers49b926b55135
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 90da940d0b2c..b765c68e683f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -199,6 +199,7 @@ the row lists both.| ezofficeinventory | HTTP | requests | ✅ || factorial | HTTP | requests + `rest_source.RESTClient` | ✅ || fastly | HTTP | requests | ✅ |+| featurebase | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || fillout | HTTP | requests + `rest_source.RESTClient` | ✅ || finage | HTTP | requests | ✅ || financial_modelling | HTTP | requests | ✅ |@@ -679,7 +680,6 @@ doesn't conflict with concurrent PRs.- facebook_pages- fastbill- fauna-- featurebase- feishu- fintoc- firebasediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/canonical_descriptions.pynew file mode 100644index 000000000000..0b21f14900ae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/canonical_descriptions.py@@ -0,0 +1,181 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Sourced from the official Featurebase API reference (https://developers.featurebase.app/api).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "posts": {+ "description": "User-submitted feedback items. Each post belongs to a board and carries a status, tags, upvotes, comments, and custom field values.",+ "docs_url": "https://developers.featurebase.app/api/resources/feedback/subresources/posts/methods/list/",+ "columns": {+ "id": "Unique identifier of the post.",+ "title": "Post title.",+ "content": "Post content in HTML format.",+ "boardId": "Board (category) ID this post belongs to.",+ "status": "Current workflow status of the post (id, name, color, type).",+ "author": "The user who submitted the post (id, name, email, type).",+ "assigneeId": "ID of the admin assigned to this post, null if unassigned.",+ "tags": "Tags attached to this post.",+ "upvotes": "Total number of upvotes.",+ "commentCount": "Total number of comments.",+ "customFields": "Custom field values keyed by field ID.",+ "eta": "Estimated completion time as an ISO 8601 timestamp, null if not set.",+ "inReview": "Whether the post is pending moderation review.",+ "isPinned": "Whether the post is pinned to the top.",+ "integrations": "Third-party integration links (GitHub, Jira, Linear, ClickUp, HubSpot, Salesforce, Azure DevOps).",+ "opportunityAmount": "Total opportunity amount from linked HubSpot deals and Salesforce opportunities.",+ "postUrl": "Full URL to view the post.",+ "slug": "URL-friendly slug.",+ "createdAt": "ISO 8601 timestamp when the post was created.",+ "updatedAt": "ISO 8601 timestamp when the post was last modified.",+ },+ },+ "boards": {+ "description": "Boards (post categories) that contain feedback posts, with access controls and feature toggles.",+ "docs_url": "https://developers.featurebase.app/api/resources/feedback/subresources/boards/methods/list/",+ "columns": {+ "id": "Unique identifier of the board.",+ "name": "Display name in the organization's default locale.",+ "access": "Access controls: adminOnly flag, allowed/denied role IDs, and segment restrictions.",+ "features": "Feature toggles: whether commenting, posting, and visible creation dates are enabled.",+ "customFields": "Custom field IDs attached to this board.",+ "postDefaults": "Default visibility for new posts (public, authorOnly, companyOnly).",+ "localization": "Localized names, descriptions, and form copy keyed by language code.",+ "createdAt": "ISO 8601 timestamp when the board was created.",+ },+ },+ "post_statuses": {+ "description": "Workflow statuses posts move through (e.g. In Review, Planned, Completed).",+ "docs_url": "https://developers.featurebase.app/api/resources/feedback/subresources/post_statuses/methods/list/",+ "columns": {+ "id": "Unique identifier of the status.",+ "name": "Display name of the status.",+ "color": "Color used for UI display.",+ "type": "Workflow stage this status represents: reviewing, unstarted, active, completed, or canceled.",+ "isDefault": "Whether this is the default status for new posts.",+ },+ },+ "comments": {+ "description": "Threaded discussions on posts and changelogs, with voting metrics and moderation flags.",+ "docs_url": "https://developers.featurebase.app/api/resources/feedback/subresources/comments/methods/list/",+ "columns": {+ "id": "Unique identifier of the comment.",+ "postId": "Post ID this comment belongs to, null for changelog comments.",+ "changelogId": "Changelog ID this comment belongs to, null for post comments.",+ "parentCommentId": "Parent comment ID for replies, null for root comments.",+ "content": "Comment content in HTML format.",+ "author": "The user who wrote the comment (id, name, type).",+ "upvotes": "Number of upvotes.",+ "downvotes": "Number of downvotes.",+ "score": "Net score (upvotes minus downvotes).",+ "isPrivate": "Whether the comment is only visible to admins.",+ "inReview": "Whether the comment is pending moderation.",+ "isDeleted": "Whether the comment is deleted.",+ "isPinned": "Whether the comment is pinned.",+ "isSpam": "Whether the comment is marked as spam.",+ "createdAt": "ISO 8601 timestamp when the comment was created.",+ "updatedAt": "ISO 8601 timestamp when the comment was last updated.",+ },+ },+ "custom_fields": {+ "description": "Custom field definitions configured in the organization, attached to boards and filled per post.",+ "docs_url": "https://developers.featurebase.app/api/resources/feedback/subresources/custom_fields/methods/list/",+ "columns": {+ "id": "Unique identifier of the field.",+ "label": "Field label displayed to users.",+ "type": "Field type: text, number, select, multi-select, checkbox, date, or file.",+ "required": "Whether the field is required.",+ "public": "Whether the field value is publicly visible.",+ "internal": "Whether the field is for internal use only.",+ "options": "Options for select/multi-select fields.",+ "placeholder": "Placeholder text for text/number fields.",+ "createdAt": "ISO timestamp when the field was created.",+ "updatedAt": "ISO timestamp when the field was last updated.",+ },+ },+ "changelogs": {+ "description": "Release notes and product updates, with per-locale translations, categories, and publishing state.",+ "docs_url": "https://developers.featurebase.app/api/resources/changelogs/methods/list/",+ "columns": {+ "id": "Unique identifier of the changelog.",+ "title": "Changelog title.",+ "content": "Content in HTML format.",+ "markdownContent": "Content in markdown format.",+ "date": "Publication date as an ISO 8601 timestamp.",+ "state": "State of the changelog: live or draft.",+ "isPublished": "Whether the changelog is published in this locale.",+ "locale": "Locale of the changelog content.",+ "publishedLocales": "Locale codes where the changelog is published.",+ "categories": "Categories the changelog belongs to.",+ "commentCount": "Number of comments.",+ "featuredImage": "Featured image URL.",+ "emailSentToSubscribers": "Whether an email notification was sent to subscribers.",+ "slug": "URL-friendly slug.",+ "url": "Public URL to view the changelog.",+ "createdAt": "ISO 8601 timestamp when the changelog was created.",+ "updatedAt": "ISO 8601 timestamp when the changelog was last updated.",+ },+ },+ "admins": {+ "description": "Admin users of the organization's Featurebase workspace.",+ "docs_url": "https://developers.featurebase.app/api/resources/organization/subresources/admins/methods/list/",+ "columns": {+ "id": "Unique identifier of the admin.",+ "name": "Admin display name.",+ "email": "Admin email address.",+ "profilePicture": "Profile picture URL.",+ "roleId": "Role ID assigned to this admin.",+ },+ },+ "companies": {+ "description": "Companies tracked in Featurebase, typically synced from your own systems, with spend and plan attributes for feedback prioritization.",+ "docs_url": "https://developers.featurebase.app/api/resources/users/subresources/companies/methods/list/",+ "columns": {+ "id": "Featurebase internal ID.",+ "companyId": "External company ID from your system.",+ "name": "Company name.",+ "monthlySpend": "Monthly spend/revenue.",+ "plan": "Plan or tier name.",+ "industry": "Industry.",+ "website": "Company website URL.",+ "companySize": "Employee headcount.",+ "linkedUsers": "Number of users linked to this company.",+ "customFields": "Custom field values.",+ "lastActivity": "ISO date of last activity.",+ "createdAt": "ISO date when the company was created.",+ "updatedAt": "ISO date when the company was last updated.",+ },+ },+ "contacts": {+ "description": "Contacts (customers and leads) who interact with your Featurebase organization.",+ "docs_url": "https://developers.featurebase.app/api/resources/users/subresources/contacts/methods/list/",+ "columns": {+ "id": "Unique identifier of the contact.",+ "userId": "External user ID from SSO, if set.",+ "email": "Contact email address.",+ "name": "Contact display name.",+ "type": "Contact type (customer or lead).",+ "companies": "Companies the contact belongs to.",+ "customFields": "Custom field values.",+ "postsCreated": "Number of posts created.",+ "commentsCreated": "Number of comments created.",+ "lastActivity": "Last activity ISO timestamp.",+ "subscribedToChangelog": "Whether the contact is subscribed to the changelog.",+ "verified": "Whether the contact's email is verified.",+ "locale": "Contact locale.",+ },+ },+ "post_voters": {+ "description": "One row per (post, voter): the users who upvoted each post, in the standard contact format.",+ "docs_url": "https://developers.featurebase.app/api/resources/feedback/subresources/posts/subresources/voters/methods/list/",+ "columns": {+ "postId": "The post this vote belongs to.",+ "id": "Unique identifier of the voting contact.",+ "name": "Voter display name.",+ "email": "Voter email address.",+ "type": "Type of user who voted (admin, customer, guest, integration, bot, lead).",+ "companies": "Companies the voter belongs to.",+ "lastActivity": "Voter's last activity ISO timestamp.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/featurebase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/featurebase.pynew file mode 100644index 000000000000..f08a480c6f56--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/featurebase.py@@ -0,0 +1,583 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import orjson+import pyarrow as pa+import requests+from asgiref.sync import async_to_sync+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 SortMode, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSyncResult,+)+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.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.settings import (+ FEATUREBASE_API_VERSION,+ FEATUREBASE_BASE_URL,+ FEATUREBASE_ENDPOINTS,+ FEATUREBASE_OBJECT_TYPE_TO_TOPICS,+ FEATUREBASE_PAGE_SIZE,+ FeaturebaseEndpointConfig,+)++POSTHOG_WEBHOOK_NAME = "PostHog data warehouse"++# Hard cap on voters pages fetched per post to bound runaway pagination in the fan-out.+MAX_VOTER_PAGES_PER_POST = 100+++class FeaturebaseRetryableError(Exception):+ pass+++class FeaturebaseResumeConfig:+ # Cursor of the next page to fetch. None means "start from the first page" — used when the+ # fan-out bookmark advances to a post whose first page has no cursor yet.+ cursor: str | None = None+ # The post currently being processed in the post_voters fan-out. A stable post-ID bookmark+ # (not a positional index) so posts created/deleted between a crash and the retry can't+ # resume us into the wrong post. None for the standard endpoints.+ post_id: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Featurebase-Version": FEATUREBASE_API_VERSION,+ "Accept": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any]) -> str:+ base = f"{FEATUREBASE_BASE_URL}{path}"+ if not params:+ return base+ return f"{base}?{urlencode(params)}"+++def _format_datetime(value: datetime | date) -> str:+ """Format as ISO 8601 with a Z suffix, matching the timestamps Featurebase returns."""+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ else:+ utc_value = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _parse_row_datetime(value: Any) -> datetime | None:+ """Parse an ISO 8601 timestamp from a response row; None for missing/unparseable values."""+ if not isinstance(value, str) or not value:+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++def _coerce_cutoff(value: Any) -> datetime | None:+ """Normalize the DB watermark to a tz-aware datetime for row comparisons."""+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ return _parse_row_datetime(value)+ return None+++def _page_predates_cutoff(items: list[dict[str, Any]], field: str, cutoff: datetime | None) -> bool:+ """True when every row on a descending-sorted page is strictly older than the watermark.++ Rows without a parseable timestamp don't count as older — an unexpected field shape must+ degrade to a full sweep, never to silently skipped data.+ """+ if cutoff is None or not items:+ return False+ values = [_parse_row_datetime(item.get(field)) for item in items]+ return all(value is not None and value < cutoff for value in values)+++@retry(+ retry=retry_if_exception_type(+ (+ FeaturebaseRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any] | list[Any]:+ response = session.get(url, headers=headers, timeout=60)++ # Featurebase documents rate limiting via 429s; back off on those and transient 5xx.+ if response.status_code == 429 or response.status_code >= 500:+ raise FeaturebaseRetryableError(f"Featurebase API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 is expected during the post_voters fan-out (a post deleted mid-sync).+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Featurebase API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()+++def _make_session(api_key: str) -> requests.Session:+ """Tracked session for every Featurebase call — metered and logged, never sample-captured.++ ``capture=False``: pulled bodies carry free-form customer content (post/comment HTML,+ admin-only comments via ``privacy=all``, contact PII) and the webhook create/list/refresh+ responses carry the ``whsec_`` signing secret in a bare ``secret`` field that the+ name-based scrubbers don't recognise. ``redact_values`` masks the API key anywhere it+ appears in logged URLs.+ """+ return make_tracked_session(redact_values=(api_key,), capture=False)+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """One cheap probe to confirm the API key is genuine.++ Featurebase returns 403 (not 401) with {"success": false, "message": "..."} for both+ missing and invalid keys, verified against the live API.+ """+ url = _build_url("/admins", {})+ try:+ response = _make_session(api_key).get(url, headers=_get_headers(api_key), timeout=10)+ except Exception as e:+ return False, f"Could not reach Featurebase: {e}"++ if response.ok:+ return True, None++ try:+ message = response.json().get("message")+ except Exception:+ message = None+ return False, message or f"Featurebase returned status {response.status_code}"+++def _build_initial_params(+ config: FeaturebaseEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if config.paginated:+ params["limit"] = FEATUREBASE_PAGE_SIZE++ field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)++ if should_use_incremental_field and config.incremental_mode and field:+ params.update(config.incremental_params_for_field.get(field, {}))+ if config.incremental_mode == "server_filter" and config.server_filter_param:+ cutoff = _coerce_cutoff(db_incremental_field_last_value)+ if cutoff is not None:+ params[config.server_filter_param] = _format_datetime(cutoff)+ else:+ params.update(config.full_refresh_params)++ params.update(config.extra_params)+ return params+++def _iter_pages(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ path: str,+ params: dict[str, Any],+ start_cursor: str | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Walk a cursor-paginated endpoint, yielding (page_items, next_cursor) tuples.++ Boards and post statuses return a bare JSON array with no envelope; everything else wraps+ rows in {"object": "list", "data": [...], "nextCursor": ...}.+ """+ cursor = start_cursor+ while True:+ page_params = {**params, **({"cursor": cursor} if cursor else {})}+ data = _fetch_page(session, _build_url(path, page_params), headers, logger)++ if isinstance(data, list):+ yield data, None+ return++ items = data.get("data", [])+ next_cursor = data.get("nextCursor")+ yield items, next_cursor++ if not next_cursor:+ return+ cursor = next_cursor+++def _get_top_level_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: FeaturebaseEndpointConfig,+ resumable_source_manager: ResumableSourceManager[FeaturebaseResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> Iterator[list[dict[str, Any]]]:+ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_cursor = resume.cursor if resume else None+ if start_cursor:+ logger.debug(f"Featurebase: resuming {config.name} from cursor={start_cursor}")++ cutoff: datetime | None = None+ cutoff_field = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)+ if should_use_incremental_field and config.incremental_mode == "desc_cutoff":+ cutoff = _coerce_cutoff(db_incremental_field_last_value)++ for items, next_cursor in _iter_pages(session, headers, logger, config.path, params, start_cursor):+ if items:+ yield items+ # 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_cursor:+ resumable_source_manager.save_state(FeaturebaseResumeConfig(cursor=next_cursor))+ # Descending sweep short-circuit: once a whole page predates the watermark, every later+ # page is older still, so stop instead of re-walking full history each incremental sync.+ if cutoff_field and _page_predates_cutoff(items, cutoff_field, cutoff):+ logger.debug(f"Featurebase: {config.name} reached incremental watermark, stopping sweep")+ return+++def _iter_post_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:+ params = {"limit": FEATUREBASE_PAGE_SIZE, "sortBy": "createdAt", "sortOrder": "asc"}+ for items, _ in _iter_pages(session, headers, logger, "/posts", params):+ for item in items:+ if item.get("id"):+ yield item["id"]+++def _get_post_voter_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: FeaturebaseEndpointConfig,+ resumable_source_manager: ResumableSourceManager[FeaturebaseResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every post, materializing upvoters as {postId, ...contact} rows.++ Voter removal has no timestamp on the API, so this table is full-refresh only; the resumable+ bookmark just lets a crashed sync pick up at the post it was processing.+ """+ post_ids = list(_iter_post_ids(session, headers, logger))++ # Resolve the saved post-ID bookmark to the slice of posts still to process. If the+ # bookmarked post no longer exists (deleted between attempts), start over from the first+ # post — merge dedupes the re-pulled rows on the composite primary key.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = post_ids+ resume_cursor: str | None = None+ if resume is not None and resume.post_id is not None and resume.post_id in post_ids:+ remaining = post_ids[post_ids.index(resume.post_id) :]+ resume_cursor = resume.cursor+ logger.debug(f"Featurebase: resuming post_voters from post_id={resume.post_id}")++ for index, post_id in enumerate(remaining):+ path = config.path.format(post_id=post_id)+ pages_fetched = 0+ try:+ for items, next_cursor in _iter_pages(+ session, headers, logger, path, {"limit": FEATUREBASE_PAGE_SIZE}, resume_cursor+ ):+ rows = [{**item, "postId": post_id} for item in items]+ if rows:+ yield rows+ if next_cursor:+ resumable_source_manager.save_state(FeaturebaseResumeConfig(cursor=next_cursor, post_id=post_id))+ pages_fetched += 1+ if pages_fetched >= MAX_VOTER_PAGES_PER_POST:+ logger.warning(+ f"Featurebase: post_voters page cap reached, truncating. post_id={post_id}, "+ f"pages={pages_fetched}"+ )+ break+ except requests.HTTPError as exc:+ # A post deleted between enumeration and this fetch 404s. Skip it rather than+ # failing the whole sync — the votes are genuinely gone.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Featurebase: post {post_id} not found while fetching voters, skipping")+ else:+ raise+ finally:+ resume_cursor = None # only the resumed-into post uses the saved cursor++ # Advance the bookmark to the next post so a crash between posts resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(FeaturebaseResumeConfig(cursor=None, post_id=remaining[index + 1]))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FeaturebaseResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = FEATUREBASE_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page (and, for the fan-out, every post) so urllib3 keeps+ # the connection alive instead of re-handshaking per request.+ session = _make_session(api_key)++ if config.fan_out_over_posts:+ yield from _get_post_voter_rows(session, headers, logger, config, resumable_source_manager)+ return++ yield from _get_top_level_rows(+ session,+ headers,+ logger,+ config,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ )+++def _resolve_sort_mode(config: FeaturebaseEndpointConfig, should_use_incremental_field: bool) -> SortMode:+ """The order rows are actually emitted in — SourceResponse.sort_mode must match it.++ Full-refresh runs sort ascending on the stable creation field. Incremental runs on+ "desc_cutoff" endpoints sweep newest-first, so the pipeline must only persist the+ watermark at successful job end. "server_filter" (changelogs) stays ascending.+ """+ if should_use_incremental_field and config.incremental_mode == "desc_cutoff":+ return "desc"+ return "asc"+++def _webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Collapse a webhook batch to the latest version of each object.++ Webhook payloads are the full notification envelope ({topic, createdAt, data: {item}}).+ Several events for the same object (e.g. post.created then post.updated) can land in one+ batch, and delta merge doesn't dedupe within a batch — keep only the newest per item id,+ shaped like the underlying API object so it merges cleanly with polled rows.+ """+ if "data" not in table.column_names:+ return table_from_py_list([])++ data_col = table.column("data").to_pylist()+ created_col = (+ table.column("createdAt").to_pylist() if "createdAt" in table.column_names else [None] * table.num_rows+ )++ best_by_id: dict[str, tuple[datetime, dict[str, Any]]] = {}+ for data, event_created in zip(data_col, created_col):+ if data is None:+ continue+ # `data` typically arrives as a nested dict (pyarrow struct), but defensively handle+ # the case where it's been serialized as a JSON string upstream.+ payload = orjson.loads(data) if isinstance(data, (str, bytes)) else dict(data)+ item = payload.get("item")+ if not isinstance(item, dict) or item.get("id") is None:+ continue+ ts = _parse_row_datetime(event_created) or datetime.min.replace(tzinfo=UTC)+ existing = best_by_id.get(item["id"])+ if existing is None or ts > existing[0]:+ best_by_id[item["id"]] = (ts, item)++ return table_from_py_list([item for _, item in best_by_id.values()])+++def featurebase_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FeaturebaseResumeConfig],+ webhook_source_manager: WebhookSourceManager,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = FEATUREBASE_ENDPOINTS[endpoint]+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)()++ def items():+ if webhook_enabled:+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)+ return get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_keys,+ sort_mode=_resolve_sort_mode(config, should_use_incremental_field),+ 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,+ )+++# --- Webhook management -------------------------------------------------------------------+++def _format_http_error(error: requests.HTTPError) -> str:+ response: requests.Response | None = error.response+ if response is None:+ return str(error)+ try:+ message = response.json().get("message")+ except Exception:+ message = None+ return message or f"Featurebase returned status {response.status_code}"+++def all_desired_webhook_topics() -> list[str]:+ return [topic for topics in FEATUREBASE_OBJECT_TYPE_TO_TOPICS.values() for topic in topics]+++def _list_webhooks(session: requests.Session, headers: dict[str, str]) -> list[dict[str, Any]]:+ webhooks: list[dict[str, Any]] = []+ cursor: str | None = None+ while True:+ params: dict[str, Any] = {"limit": FEATUREBASE_PAGE_SIZE, **({"cursor": cursor} if cursor else {})}+ response = session.get(_build_url("/webhooks", params), headers=headers, timeout=30)+ response.raise_for_status()+ data = response.json()+ webhooks.extend(data.get("data", []))+ cursor = data.get("nextCursor")+ if not cursor:+ return webhooks+++def _find_webhook_by_url(webhooks: list[dict[str, Any]], webhook_url: str) -> dict[str, Any] | None:+ for webhook in webhooks:+ if webhook.get("url") == webhook_url:+ return webhook+ return None+++def create_webhook(api_key: str, webhook_url: str) -> WebhookCreationResult:+ session = _make_session(api_key)+ headers = _get_headers(api_key)+ payload = {+ "name": POSTHOG_WEBHOOK_NAME,+ "url": webhook_url,+ "description": "Streams Featurebase events into the PostHog data warehouse",+ "topics": all_desired_webhook_topics(),+ }+ try:+ response = session.post(_build_url("/webhooks", {}), headers=headers, json=payload, timeout=30)+ response.raise_for_status()+ except requests.HTTPError as e:+ # Featurebase caps webhooks per organization (default 10) and returns 400 at the cap.+ return WebhookCreationResult(success=False, error=_format_http_error(e))+ except requests.RequestException as e:+ return WebhookCreationResult(success=False, error=f"Could not reach Featurebase: {e}")++ # The create response includes the signing secret; persist it onto the hog function so the+ # template can verify X-Webhook-Signature without any manual setup.+ secret = response.json().get("secret")+ extra_inputs: dict[str, Any] = {"signing_secret": secret} if secret else {}+ return WebhookCreationResult(+ success=True, extra_inputs=extra_inputs, pending_inputs=[] if secret else ["signing_secret"]+ )+++def sync_webhook_events(api_key: str, webhook_url: str, desired_topics: list[str]) -> WebhookSyncResult:+ session = _make_session(api_key)+ headers = _get_headers(api_key)+ try:+ webhook = _find_webhook_by_url(_list_webhooks(session, headers), webhook_url)+ if webhook is None:+ return WebhookSyncResult(success=False, error="No Featurebase webhook found for this source")+ if set(webhook.get("topics", [])) == set(desired_topics):+ return WebhookSyncResult(success=True)+ response = session.patch(+ _build_url(f"/webhooks/{webhook['id']}", {}),+ headers=headers,+ json={"topics": desired_topics},+ timeout=30,+ )+ response.raise_for_status()+ except requests.HTTPError as e:+ return WebhookSyncResult(success=False, error=_format_http_error(e))+ except requests.RequestException as e:+ return WebhookSyncResult(success=False, error=f"Could not reach Featurebase: {e}")+ return WebhookSyncResult(success=True)+++def get_external_webhook_info(api_key: str, webhook_url: str) -> ExternalWebhookInfo:+ session = _make_session(api_key)+ headers = _get_headers(api_key)+ try:+ webhook = _find_webhook_by_url(_list_webhooks(session, headers), webhook_url)+ except requests.HTTPError as e:+ return ExternalWebhookInfo(exists=False, error=_format_http_error(e))+ except requests.RequestException as e:+ return ExternalWebhookInfo(exists=False, error=f"Could not reach Featurebase: {e}")++ if webhook is None:+ return ExternalWebhookInfo(exists=False)++ return ExternalWebhookInfo(+ exists=True,+ url=webhook.get("url"),+ enabled_events=webhook.get("topics"),+ status=webhook.get("status"),+ description=webhook.get("description"),+ created_at=webhook.get("createdAt"),+ )+++def delete_webhook(api_key: str, webhook_url: str) -> WebhookDeletionResult:+ session = _make_session(api_key)+ headers = _get_headers(api_key)+ try:+ webhook = _find_webhook_by_url(_list_webhooks(session, headers), webhook_url)+ if webhook is None:+ # Nothing to delete — treat as success, matching the Stripe/GitHub sources.+ return WebhookDeletionResult(success=True)+ response = session.delete(_build_url(f"/webhooks/{webhook['id']}", {}), headers=headers, timeout=30)+ if response.status_code == 404:+ return WebhookDeletionResult(success=True)+ response.raise_for_status()+ except requests.HTTPError as e:+ return WebhookDeletionResult(success=False, error=_format_http_error(e))+ except requests.RequestException as e:+ return WebhookDeletionResult(success=False, error=f"Could not reach Featurebase: {e}")+ return WebhookDeletionResult(success=True)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/settings.pynew file mode 100644index 000000000000..93b7ee2f5ccc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/settings.py@@ -0,0 +1,171 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++FEATUREBASE_BASE_URL = "https://do.featurebase.app/v2"+FEATUREBASE_API_VERSION = "2026-01-01.nova"++# Featurebase caps `limit` at 100 on every cursor-paginated list endpoint.+FEATUREBASE_PAGE_SIZE = 100++# Maps PostHog webhook-backed schema name -> the `data.item.object` value of incoming webhook+# payloads, used to route events into the right warehouse table. Deleted-object topics are+# intentionally not subscribed: their payload is the object at deletion time, and merging it+# back on the primary key would resurrect the row. Deletions reconcile on a full refresh.+RESOURCE_TO_FEATUREBASE_OBJECT_TYPE: dict[str, str] = {+ "posts": "post",+ "comments": "comment",+ "changelogs": "changelog",+}++FEATUREBASE_OBJECT_TYPE_TO_TOPICS: dict[str, tuple[str, ...]] = {+ "post": ("post.created", "post.updated"),+ "comment": ("comment.created", "comment.updated"),+ "changelog": ("changelog.published",),+}+++@dataclass+class FeaturebaseEndpointConfig:+ name: str+ path: str # Relative to FEATUREBASE_BASE_URL; may carry a {post_id} placeholder for fan-out+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # How incremental sync is achieved for this endpoint:+ # - "desc_cutoff": no server-side timestamp filter exists, but the endpoint supports a+ # descending sort on the incremental field, so the sweep short-circuits once a whole+ # page predates the watermark (same pattern as the GitHub source).+ # - "server_filter": the endpoint accepts a genuine server-side lower-bound param+ # (changelogs' `startDate`) and an ascending sort, so only new rows are fetched.+ # - None: full refresh only.+ incremental_mode: Optional[Literal["desc_cutoff", "server_filter"]] = None+ # Maps incremental field name -> the query params that sort by it in the direction the+ # incremental mode needs (descending for "desc_cutoff", ascending for "server_filter").+ incremental_params_for_field: dict[str, dict[str, str]] = field(default_factory=dict)+ # Server-side lower-bound query param for "server_filter" endpoints (changelogs' startDate).+ server_filter_param: Optional[str] = None+ # Query params for a full-refresh run (stable ascending sort where the endpoint has one).+ full_refresh_params: dict[str, str] = field(default_factory=dict)+ # Extra query params merged into every request (e.g. privacy=all).+ extra_params: dict[str, str] = field(default_factory=dict)+ # Whether the endpoint paginates with limit/cursor. Boards and post statuses return+ # everything in one response (boards as a bare JSON array, no `data` envelope).+ paginated: bool = True+ partition_key: Optional[str] = None # Stable creation-time field, never updatedAt+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ # Fan out one voters request per post ({post_id} placeholder in path).+ fan_out_over_posts: bool = False+++_CREATED_AT_FIELD: IncrementalField = {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+}++_UPDATED_AT_FIELD: IncrementalField = {+ "label": "updatedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "updatedAt",+ "field_type": IncrementalFieldType.DateTime,+}++FEATUREBASE_ENDPOINTS: dict[str, FeaturebaseEndpointConfig] = {+ "posts": FeaturebaseEndpointConfig(+ name="posts",+ path="/posts",+ partition_key="createdAt",+ incremental_mode="desc_cutoff",+ # `recent` is documented as "sort by most recently updated"; `createdAt` sorts by+ # creation date. Both accept sortOrder=asc|desc.+ incremental_params_for_field={+ "updatedAt": {"sortBy": "recent", "sortOrder": "desc"},+ "createdAt": {"sortBy": "createdAt", "sortOrder": "desc"},+ },+ full_refresh_params={"sortBy": "createdAt", "sortOrder": "asc"},+ incremental_fields=[_UPDATED_AT_FIELD, _CREATED_AT_FIELD],+ ),+ "comments": FeaturebaseEndpointConfig(+ name="comments",+ path="/comments",+ partition_key="createdAt",+ incremental_mode="desc_cutoff",+ # Comments have their own sort enum: "new" = creation date newest-first,+ # "old" = creation date oldest-first. No updatedAt sort or sortOrder param exists.+ incremental_params_for_field={"createdAt": {"sortBy": "new"}},+ full_refresh_params={"sortBy": "old"},+ # Include admin-only comments; the API key is org-scoped so the caller owns the data.+ extra_params={"privacy": "all"},+ incremental_fields=[_CREATED_AT_FIELD],+ ),+ "changelogs": FeaturebaseEndpointConfig(+ name="changelogs",+ path="/changelogs",+ partition_key="createdAt",+ incremental_mode="server_filter",+ # `startDate` is inclusive ("dated on or after"), so the watermark row is re-pulled+ # and deduped by merge. Only `date` (publication date) is filterable server-side.+ incremental_params_for_field={"date": {"sortBy": "date", "sortOrder": "asc"}},+ server_filter_param="startDate",+ full_refresh_params={"sortBy": "date", "sortOrder": "asc"},+ incremental_fields=[+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ ),+ "boards": FeaturebaseEndpointConfig(+ name="boards",+ path="/boards",+ paginated=False,+ ),+ "post_statuses": FeaturebaseEndpointConfig(+ name="post_statuses",+ path="/post_statuses",+ paginated=False,+ ),+ "custom_fields": FeaturebaseEndpointConfig(+ name="custom_fields",+ path="/custom_fields",+ # Documented as returning everything at once ({data: [...], nextCursor: null});+ # the standard cursor loop terminates on the null cursor either way.+ ),+ "admins": FeaturebaseEndpointConfig(+ name="admins",+ path="/admins",+ ),+ "companies": FeaturebaseEndpointConfig(+ name="companies",+ path="/companies",+ partition_key="createdAt",+ ),+ "contacts": FeaturebaseEndpointConfig(+ name="contacts",+ path="/contacts",+ # Default is customers only; pull leads too so the table covers every identity+ # that can author posts and comments.+ extra_params={"contactType": "all"},+ ),+ # One request per post: materializes the post<->upvoter many-to-many as+ # {postId, ...contact} rows. Opt-in (off by default) because it costs one paginated+ # request chain per post. Voter ids are contact ids (unique per org, not per post),+ # so the composite key keeps rows unique table-wide.+ "post_voters": FeaturebaseEndpointConfig(+ name="post_voters",+ path="/posts/{post_id}/voters",+ fan_out_over_posts=True,+ primary_keys=["postId", "id"],+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(FEATUREBASE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FEATUREBASE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/source.pyindex 51b1dac2388b..619af2496377 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/source.py@@ -1,19 +1,64 @@-from typing import cast+from typing import TYPE_CHECKING, 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 (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)+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.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.featurebase import (+ FeaturebaseResumeConfig,+ all_desired_webhook_topics,+ create_webhook as create_featurebase_webhook,+ delete_webhook as delete_featurebase_webhook,+ featurebase_source,+ get_external_webhook_info as get_featurebase_webhook_info,+ sync_webhook_events as sync_featurebase_webhook_events,+ validate_credentials as validate_featurebase_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.settings import (+ ENDPOINTS,+ FEATUREBASE_ENDPOINTS,+ INCREMENTAL_FIELDS,+ RESOURCE_TO_FEATUREBASE_OBJECT_TYPE,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FeaturebaseSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+@SourceRegistry.register-class FeaturebaseSource(SimpleSource[FeaturebaseSourceConfig]):+class FeaturebaseSource(+ ResumableSource[FeaturebaseSourceConfig, FeaturebaseResumeConfig],+ WebhookSource[FeaturebaseSourceConfig],+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FEATUREBASE@@ -24,7 +69,182 @@ class FeaturebaseSource(SimpleSource[FeaturebaseSourceConfig]):name=SchemaExternalDataSourceType.FEATUREBASE,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Featurebase",+ releaseStatus=ReleaseStatus.ALPHA,+ caption=(+ "Enter your Featurebase API key to pull your feedback posts, boards, comments, "+ "upvoters, changelogs, and users into the PostHog Data warehouse.\n\n"+ "You can create an API key in your Featurebase dashboard under "+ "**Settings** > **API**."+ ),iconPath="/static/services/featurebase.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/featurebase",+ keywords=["feedback", "roadmap", "changelog"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Featurebase API key",+ secret=True,+ ),+ ],+ ),+ webhookSetupCaption=(+ "PostHog registers the Featurebase webhook for you using your API key, including "+ "the signing secret — no manual steps needed.\n\n"+ "**Manual setup** (only needed if auto-registration failed, e.g. your organization "+ "hit Featurebase's webhook limit):\n\n"+ "1. In Featurebase, go to **Settings** > **Webhooks** > **Add webhook**\n"+ "2. Paste the webhook URL shown below into the **URL** field\n"+ "3. Subscribe to the post, comment, and changelog topics\n"+ "4. Copy the **Signing secret** into the field below"+ ),+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="whsec_...",+ secret=True,+ ),+ ],+ ),+ )++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.webhook_template import (+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return RESOURCE_TO_FEATUREBASE_OBJECT_TYPE++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Featurebase responds 403 for missing/invalid API keys (verified against the live+ # API); 401 is matched too in case that ever changes. Retrying can never satisfy a+ # credential problem, so stop the sync.+ return {+ "401 Client Error: Unauthorized for url: https://do.featurebase.app": (+ "Your Featurebase API key is invalid or has been revoked. Create a new API key in "+ "your Featurebase dashboard under Settings > API, then reconnect."+ ),+ "403 Client Error: Forbidden for url: https://do.featurebase.app": (+ "Featurebase rejected your API key. Create a new API key in your Featurebase "+ "dashboard under Settings > API, then reconnect."+ ),+ }++ def get_schemas(+ self,+ config: FeaturebaseSourceConfig,+ 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 == "post_voters":+ return (+ "Maps which users upvoted which post as one row per (post, voter). "+ "Costs one request chain per post, so it's off by default"+ )+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = FEATUREBASE_ENDPOINTS[endpoint]+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ # All resources are mutable (posts/comments get edited, changelogs republished),+ # so merge is the only safe write disposition — append would duplicate rows.+ supports_append=False,+ supports_webhooks=endpoint in RESOURCE_TO_FEATUREBASE_OBJECT_TYPE,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ 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: FeaturebaseSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ valid, error = validate_featurebase_credentials(config.api_key)+ if valid:+ return True, None+ return False, error or "Invalid Featurebase API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FeaturebaseResumeConfig]:+ return ResumableSourceManager[FeaturebaseResumeConfig](inputs, FeaturebaseResumeConfig)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(self, config: FeaturebaseSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:+ return create_featurebase_webhook(config.api_key, webhook_url)++ def get_desired_webhook_events(+ self, config: FeaturebaseSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ # Every mappable topic, not just the selected tables — auto-heals webhooks created+ # before a table was enabled; unmapped events are dropped by the hog function.+ return all_desired_webhook_topics()++ def sync_webhook_events(+ self,+ config: FeaturebaseSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ ) -> WebhookSyncResult:+ desired_topics = self.get_desired_webhook_events(config, eligible_schema_names) or []+ return sync_featurebase_webhook_events(config.api_key, webhook_url, desired_topics)++ def get_external_webhook_info(+ self, config: FeaturebaseSourceConfig, webhook_url: str, team_id: int+ ) -> ExternalWebhookInfo | None:+ return get_featurebase_webhook_info(config.api_key, webhook_url)++ def delete_webhook(self, config: FeaturebaseSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:+ return delete_featurebase_webhook(config.api_key, webhook_url)++ def source_for_pipeline(+ self,+ config: FeaturebaseSourceConfig,+ resumable_source_manager: ResumableSourceManager[FeaturebaseResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return featurebase_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/tests/test_featurebase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/tests/test_featurebase.pynew file mode 100644index 000000000000..3aa47a017365--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/tests/test_featurebase.py@@ -0,0 +1,612 @@+from datetime import UTC, datetime+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.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase import featurebase+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.featurebase import (+ FeaturebaseResumeConfig,+ _build_initial_params,+ _page_predates_cutoff,+ _webhook_table_transformer,+ create_webhook,+ delete_webhook,+ featurebase_source,+ get_external_webhook_info,+ get_rows,+ sync_webhook_events,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.settings import FEATUREBASE_ENDPOINTS++BASE = "https://do.featurebase.app/v2"+++class _FakeResumableManager:+ def __init__(self, state: FeaturebaseResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[FeaturebaseResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> FeaturebaseResumeConfig | None:+ return self._state++ def save_state(self, data: FeaturebaseResumeConfig) -> 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_rows(+ monkeypatch: Any,+ endpoint: str,+ pages: dict[str, Any],+ manager: _FakeResumableManager | None = None,+ fetched_urls: list[str] | None = None,+ **incremental: Any,+) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ if fetched_urls is not None:+ fetched_urls.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(featurebase, "_fetch_page", fake_fetch)+ monkeypatch.setattr(featurebase, "make_tracked_session", MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="fb_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager or _FakeResumableManager(), # type: ignore[arg-type]+ **incremental,+ ):+ rows.extend(batch)+ return rows+++class TestBuildInitialParams:+ @parameterized.expand(+ [+ (+ "posts_full_refresh_sorts_ascending_by_created",+ "posts",+ False,+ None,+ {"limit": 100, "sortBy": "createdAt", "sortOrder": "asc"},+ ),+ (+ "posts_incremental_updated_sweeps_recent_desc",+ "posts",+ True,+ "updatedAt",+ {"limit": 100, "sortBy": "recent", "sortOrder": "desc"},+ ),+ (+ "posts_incremental_created_sweeps_created_desc",+ "posts",+ True,+ "createdAt",+ {"limit": 100, "sortBy": "createdAt", "sortOrder": "desc"},+ ),+ (+ "comments_incremental_uses_new_sort_enum",+ "comments",+ True,+ "createdAt",+ {"limit": 100, "sortBy": "new", "privacy": "all"},+ ),+ (+ "comments_full_refresh_uses_old_sort_enum",+ "comments",+ False,+ None,+ {"limit": 100, "sortBy": "old", "privacy": "all"},+ ),+ (+ "boards_has_no_pagination_params",+ "boards",+ False,+ None,+ {},+ ),+ ]+ )+ def test_build_initial_params(+ self, _name: str, endpoint: str, incremental: bool, field: str | None, expected: dict+ ) -> None:+ params = _build_initial_params(+ FEATUREBASE_ENDPOINTS[endpoint],+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=None,+ incremental_field=field,+ )+ assert params == expected++ def test_changelogs_incremental_sends_server_side_start_date(self) -> None:+ params = _build_initial_params(+ FEATUREBASE_ENDPOINTS["changelogs"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field="date",+ )+ assert params["startDate"] == "2026-03-04T02:58:14.000Z"+ assert params["sortBy"] == "date"+ assert params["sortOrder"] == "asc"++ def test_changelogs_first_incremental_sync_has_no_start_date(self) -> None:+ params = _build_initial_params(+ FEATUREBASE_ENDPOINTS["changelogs"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="date",+ )+ assert "startDate" not in params+++class TestPagePredatesCutoff:+ _cutoff = datetime(2026, 1, 10, tzinfo=UTC)++ @parameterized.expand(+ [+ (+ "whole_page_older_stops_the_sweep",+ [{"createdAt": "2026-01-05T00:00:00.000Z"}, {"createdAt": "2026-01-01T00:00:00.000Z"}],+ True,+ ),+ (+ "page_with_newer_row_keeps_sweeping",+ [{"createdAt": "2026-01-15T00:00:00.000Z"}, {"createdAt": "2026-01-01T00:00:00.000Z"}],+ False,+ ),+ (+ "unparseable_field_degrades_to_full_sweep",+ [{"createdAt": None}, {"createdAt": "2026-01-01T00:00:00.000Z"}],+ False,+ ),+ ("empty_page_never_stops", [], False),+ ]+ )+ def test_page_predates_cutoff(self, _name: str, items: list[dict], expected: bool) -> None:+ assert _page_predates_cutoff(items, "createdAt", self._cutoff) is expected++ def test_no_watermark_never_stops(self) -> None:+ assert _page_predates_cutoff([{"createdAt": "2020-01-01T00:00:00.000Z"}], "createdAt", None) is False+++class TestFetchPageRetries:+ def test_429_is_retried_until_success(self) -> None:+ throttled = MagicMock(status_code=429)+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"data": []}+ session = MagicMock()+ session.get.side_effect = [throttled, good]++ with patch.object(featurebase._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = featurebase._fetch_page(session, f"{BASE}/posts", {}, MagicMock())++ assert result == {"data": []}+ assert session.get.call_count == 2++ def test_auth_error_is_not_retried(self) -> None:+ forbidden = MagicMock(status_code=403, ok=False, text='{"success":false,"message":"Invalid API Key"}')+ forbidden.raise_for_status.side_effect = requests.HTTPError(response=_response_with_status(403))+ session = MagicMock()+ session.get.return_value = forbidden++ with patch.object(featurebase._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(requests.HTTPError):+ featurebase._fetch_page(session, f"{BASE}/posts", {}, MagicMock())++ assert session.get.call_count == 1+++class TestCursorPagination:+ def test_follows_next_cursor_and_saves_state_after_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ f"{BASE}/companies?limit=100": {"data": [{"id": "c1"}], "nextCursor": "cur2"},+ f"{BASE}/companies?limit=100&cursor=cur2": {"data": [{"id": "c2"}], "nextCursor": None},+ }+ rows = _collect_rows(monkeypatch, "companies", pages, manager)++ assert [r["id"] for r in rows] == ["c1", "c2"]+ # State only saved while more pages remain — a crash on the final page restarts it cleanly.+ assert [s.cursor for s in manager.saved] == ["cur2"]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(FeaturebaseResumeConfig(cursor="cur2"))+ fetched: list[str] = []+ pages = {+ f"{BASE}/companies?limit=100&cursor=cur2": {"data": [{"id": "c2"}], "nextCursor": None},+ }+ rows = _collect_rows(monkeypatch, "companies", pages, manager, fetched_urls=fetched)++ assert [r["id"] for r in rows] == ["c2"]+ assert fetched == [f"{BASE}/companies?limit=100&cursor=cur2"]++ def test_bare_array_endpoint_yields_single_batch(self, monkeypatch: Any) -> None:+ pages = {f"{BASE}/boards": [{"id": "b1", "object": "board"}]}+ rows = _collect_rows(monkeypatch, "boards", pages)+ assert rows == [{"id": "b1", "object": "board"}]+++class TestDescCutoffIncremental:+ def test_sweep_stops_once_page_predates_watermark(self, monkeypatch: Any) -> None:+ # Page 3 must never be fetched: page 2 is entirely older than the watermark, and a+ # newest-first sweep that keeps walking would re-fetch full history every sync.+ fetched: list[str] = []+ pages = {+ f"{BASE}/posts?limit=100&sortBy=recent&sortOrder=desc": {+ "data": [{"id": "p1", "updatedAt": "2026-01-15T00:00:00.000Z"}],+ "nextCursor": "cur2",+ },+ f"{BASE}/posts?limit=100&sortBy=recent&sortOrder=desc&cursor=cur2": {+ "data": [{"id": "p2", "updatedAt": "2026-01-05T00:00:00.000Z"}],+ "nextCursor": "cur3",+ },+ }+ rows = _collect_rows(+ monkeypatch,+ "posts",+ pages,+ fetched_urls=fetched,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),+ incremental_field="updatedAt",+ )++ # The boundary page is still yielded (merge dedupes re-pulled rows on the primary key).+ assert [r["id"] for r in rows] == ["p1", "p2"]+ assert len(fetched) == 2++ def test_first_incremental_sync_walks_everything(self, monkeypatch: Any) -> None:+ fetched: list[str] = []+ pages = {+ f"{BASE}/posts?limit=100&sortBy=recent&sortOrder=desc": {+ "data": [{"id": "p1", "updatedAt": "2026-01-15T00:00:00.000Z"}],+ "nextCursor": "cur2",+ },+ f"{BASE}/posts?limit=100&sortBy=recent&sortOrder=desc&cursor=cur2": {+ "data": [{"id": "p2", "updatedAt": "2026-01-05T00:00:00.000Z"}],+ "nextCursor": None,+ },+ }+ rows = _collect_rows(+ monkeypatch,+ "posts",+ pages,+ fetched_urls=fetched,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="updatedAt",+ )+ assert [r["id"] for r in rows] == ["p1", "p2"]+ assert len(fetched) == 2+++class TestPostVotersFanOut:+ _posts_url = f"{BASE}/posts?limit=100&sortBy=createdAt&sortOrder=asc"++ def test_config_is_opt_in_fan_out_with_composite_pk(self) -> None:+ config = FEATUREBASE_ENDPOINTS["post_voters"]+ assert config.fan_out_over_posts is True+ assert config.should_sync_default is False+ assert config.primary_keys == ["postId", "id"]++ def test_fans_out_over_every_post_injecting_post_id(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ self._posts_url: {"data": [{"id": "P1"}, {"id": "P2"}], "nextCursor": None},+ f"{BASE}/posts/P1/voters?limit=100": {+ "data": [{"id": "U1", "object": "contact"}],+ "nextCursor": None,+ },+ f"{BASE}/posts/P2/voters?limit=100": {+ "data": [{"id": "U1", "object": "contact"}, {"id": "U2", "object": "contact"}],+ "nextCursor": None,+ },+ }+ rows = _collect_rows(monkeypatch, "post_voters", pages, manager)++ assert [(r["postId"], r["id"]) for r in rows] == [("P1", "U1"), ("P2", "U1"), ("P2", "U2")]+ # Bookmark advanced to P2 so a crash between posts resumes there, not from scratch.+ assert [(s.post_id, s.cursor) for s in manager.saved] == [("P2", None)]++ def test_deleted_post_404_is_skipped(self, monkeypatch: Any) -> None:+ not_found = requests.HTTPError(response=_response_with_status(404))+ pages = {+ self._posts_url: {"data": [{"id": "P1"}, {"id": "P2"}], "nextCursor": None},+ f"{BASE}/posts/P1/voters?limit=100": not_found,+ f"{BASE}/posts/P2/voters?limit=100": {"data": [{"id": "U2"}], "nextCursor": None},+ }+ rows = _collect_rows(monkeypatch, "post_voters", pages)+ assert [(r["postId"], r["id"]) for r in rows] == [("P2", "U2")]++ def test_non_404_error_propagates(self, monkeypatch: Any) -> None:+ server_error = requests.HTTPError(response=_response_with_status(500))+ pages = {+ self._posts_url: {"data": [{"id": "P1"}], "nextCursor": None},+ f"{BASE}/posts/P1/voters?limit=100": server_error,+ }+ with pytest.raises(requests.HTTPError):+ _collect_rows(monkeypatch, "post_voters", pages)++ def test_resumes_from_bookmarked_post(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(FeaturebaseResumeConfig(cursor="vcur", post_id="P2"))+ fetched: list[str] = []+ pages = {+ self._posts_url: {"data": [{"id": "P1"}, {"id": "P2"}], "nextCursor": None},+ f"{BASE}/posts/P2/voters?limit=100&cursor=vcur": {"data": [{"id": "U9"}], "nextCursor": None},+ }+ rows = _collect_rows(monkeypatch, "post_voters", pages, manager, fetched_urls=fetched)++ # P1 was already synced before the crash: only the bookmarked post is re-fetched,+ # starting at its saved cursor.+ assert [(r["postId"], r["id"]) for r in rows] == [("P2", "U9")]+ assert f"{BASE}/posts/P1/voters?limit=100" not in fetched+++class TestSourceResponse:+ def _source(self, endpoint: str, should_use_incremental_field: bool = False) -> Any:+ webhook_manager = MagicMock()+ webhook_manager.webhook_enabled = MagicMock(return_value=False)+ with patch.object(featurebase, "async_to_sync", lambda fn: fn):+ return featurebase_source(+ api_key="fb_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ webhook_source_manager=webhook_manager,+ should_use_incremental_field=should_use_incremental_field,+ )++ @parameterized.expand(+ [+ # Incremental desc sweeps must defer watermark persistence to job end; per-batch+ # "asc" persistence on a newest-first stream would checkpoint ≈now after batch one.+ ("posts_incremental", "posts", True, "desc"),+ ("posts_full_refresh", "posts", False, "asc"),+ ("changelogs_incremental_stays_asc", "changelogs", True, "asc"),+ ("boards_full_refresh", "boards", False, "asc"),+ ]+ )+ def test_sort_mode_matches_emit_order(self, _name: str, endpoint: str, incremental: bool, expected: str) -> None:+ assert self._source(endpoint, incremental).sort_mode == expected++ @parameterized.expand(+ [+ ("posts", ["id"], ["createdAt"]),+ ("post_voters", ["postId", "id"], None),+ ("contacts", ["id"], None),+ ]+ )+ def test_primary_and_partition_keys(+ self, endpoint: str, expected_pk: list[str], expected_partition: list[str] | None+ ) -> None:+ response = self._source(endpoint)+ assert response.primary_keys == expected_pk+ assert response.partition_keys == expected_partition+++class TestWebhookTableTransformer:+ def test_keeps_only_latest_event_per_object(self) -> None:+ # post.created then post.updated for the same post in one batch: delta merge doesn't+ # dedupe within a batch, so only the newest version may survive.+ table = table_from_py_list(+ [+ {+ "id": "notif_1",+ "topic": "post.created",+ "createdAt": "2026-01-01T00:00:00.000Z",+ "data": {"item": {"id": "p1", "object": "post", "title": "old title"}},+ },+ {+ "id": "notif_2",+ "topic": "post.updated",+ "createdAt": "2026-01-02T00:00:00.000Z",+ "data": {"item": {"id": "p1", "object": "post", "title": "new title"}},+ },+ {+ "id": "notif_3",+ "topic": "post.created",+ "createdAt": "2026-01-01T12:00:00.000Z",+ "data": {"item": {"id": "p2", "object": "post", "title": "other post"}},+ },+ ]+ )+ rows = sorted(_webhook_table_transformer(table).to_pylist(), key=lambda r: r["id"])+ assert rows == [+ {"id": "p1", "object": "post", "title": "new title"},+ {"id": "p2", "object": "post", "title": "other post"},+ ]++ def test_rows_without_item_id_are_dropped(self) -> None:+ table = table_from_py_list(+ [+ {"id": "notif_1", "createdAt": "2026-01-01T00:00:00.000Z", "data": {"item": {"title": "no id"}}},+ {"id": "notif_2", "createdAt": "2026-01-01T00:00:00.000Z", "data": None},+ ]+ )+ assert _webhook_table_transformer(table).to_pylist() == []+++def _session_with(**methods: Any) -> MagicMock:+ session = MagicMock()+ for name, value in methods.items():+ getattr(session, name).side_effect = value if isinstance(value, list) else [value]+ return session+++def _json_response(payload: Any, status_code: int = 200) -> MagicMock:+ response = MagicMock(status_code=status_code, ok=status_code < 400)+ response.json.return_value = payload+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(response=response)+ else:+ response.raise_for_status.return_value = None+ return response+++class TestSessionSampleCapture:+ # Featurebase bodies carry free-form customer content (posts/comments HTML, admin-only+ # comments, contact PII) and the webhook create/list responses carry the whsec_ signing+ # secret in a bare `secret` field that the name-based scrubbers don't redact. Reverting+ # capture=False re-exposes those bodies to HTTP sample capture.+ @parameterized.expand(+ [+ (+ "polling",+ lambda: list(+ get_rows("fb_test", "boards", MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ ),+ ),+ ("validate_credentials", lambda: validate_credentials("fb_test")),+ ("webhook_management", lambda: delete_webhook("fb_test", "https://us.posthog.com/webhook")),+ ]+ )+ def test_sessions_disable_sample_capture_and_redact_api_key(self, _name: str, trigger: Any) -> None:+ response = MagicMock(status_code=200, ok=True)+ response.json.return_value = {"data": [], "nextCursor": None}+ session = MagicMock()+ session.get.return_value = response++ with patch.object(featurebase, "make_tracked_session", return_value=session) as session_factory:+ trigger()++ assert session_factory.call_count >= 1+ for call in session_factory.call_args_list:+ assert call.kwargs == {"redact_values": ("fb_test",), "capture": False}+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid_key", 200, {"data": []}, True),+ # Featurebase responds 403 (not 401) for both missing and invalid keys.+ ("invalid_key", 403, {"success": False, "message": "Invalid API Key"}, False),+ ]+ )+ def test_validate_credentials(self, _name: str, status: int, payload: dict, expected_valid: bool) -> None:+ session = _session_with(get=_json_response(payload, status))+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ valid, error = validate_credentials("fb_test")+ assert valid is expected_valid+ if not expected_valid:+ assert error == "Invalid API Key"+++class TestWebhookManagement:+ def test_create_webhook_captures_signing_secret(self) -> None:+ session = _session_with(post=_json_response({"id": "wh1", "secret": "whsec_abc"}))+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ result = create_webhook("fb_test", "https://us.posthog.com/webhook")++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "whsec_abc"}+ assert result.pending_inputs == []+ payload = session.post.call_args.kwargs["json"]+ assert payload["url"] == "https://us.posthog.com/webhook"+ assert "post.created" in payload["topics"] and "changelog.published" in payload["topics"]++ def test_create_webhook_surfaces_org_limit_error(self) -> None:+ # Featurebase caps webhooks per org and 400s at the cap — the user needs the reason,+ # not a retry loop.+ session = _session_with(post=_json_response({"message": "Webhook limit reached"}, 400))+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ result = create_webhook("fb_test", "https://us.posthog.com/webhook")++ assert result.success is False+ assert result.error == "Webhook limit reached"++ def test_delete_webhook_matches_by_url(self) -> None:+ session = _session_with(+ get=_json_response({"data": [{"id": "wh1", "url": "https://us.posthog.com/webhook"}], "nextCursor": None}),+ delete=_json_response({"id": "wh1", "deleted": True}),+ )+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ result = delete_webhook("fb_test", "https://us.posthog.com/webhook")++ assert result.success is True+ assert "/webhooks/wh1" in session.delete.call_args.args[0]++ def test_delete_webhook_with_no_match_is_success(self) -> None:+ session = _session_with(get=_json_response({"data": [], "nextCursor": None}))+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ result = delete_webhook("fb_test", "https://us.posthog.com/webhook")+ assert result.success is True+ session.delete.assert_not_called()++ def test_sync_webhook_events_patches_drifted_topics(self) -> None:+ session = _session_with(+ get=_json_response(+ {+ "data": [{"id": "wh1", "url": "https://us.posthog.com/webhook", "topics": ["post.created"]}],+ "nextCursor": None,+ }+ ),+ patch=_json_response({"id": "wh1"}),+ )+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ result = sync_webhook_events("fb_test", "https://us.posthog.com/webhook", ["post.created", "post.updated"])++ assert result.success is True+ assert session.patch.call_args.kwargs["json"] == {"topics": ["post.created", "post.updated"]}++ def test_sync_webhook_events_noop_when_topics_match(self) -> None:+ session = _session_with(+ get=_json_response(+ {+ "data": [{"id": "wh1", "url": "https://us.posthog.com/webhook", "topics": ["post.created"]}],+ "nextCursor": None,+ }+ )+ )+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ result = sync_webhook_events("fb_test", "https://us.posthog.com/webhook", ["post.created"])+ assert result.success is True+ session.patch.assert_not_called()++ def test_get_external_webhook_info(self) -> None:+ session = _session_with(+ get=_json_response(+ {+ "data": [+ {+ "id": "wh1",+ "url": "https://us.posthog.com/webhook",+ "topics": ["post.created"],+ "status": "active",+ "createdAt": "2026-01-01T00:00:00.000Z",+ }+ ],+ "nextCursor": None,+ }+ )+ )+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ info = get_external_webhook_info("fb_test", "https://us.posthog.com/webhook")++ assert info.exists is True+ assert info.status == "active"+ assert info.enabled_events == ["post.created"]++ def test_get_external_webhook_info_not_found(self) -> None:+ session = _session_with(get=_json_response({"data": [], "nextCursor": None}))+ with patch.object(featurebase, "make_tracked_session", return_value=session):+ info = get_external_webhook_info("fb_test", "https://us.posthog.com/webhook")+ assert info.exists is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/tests/test_featurebase_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/tests/test_featurebase_source.pynew file mode 100644index 000000000000..d4c0f6a457d6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/tests/test_featurebase_source.py@@ -0,0 +1,228 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.featurebase import (+ FeaturebaseResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.source import FeaturebaseSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.featurebase.source"+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "posts",+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestFeaturebaseSource:+ def setup_method(self) -> None:+ self.source = FeaturebaseSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FEATUREBASE++ def test_source_config_is_released_with_api_key_field(self) -> None:+ config = self.source.get_source_config+ assert config.name == SchemaExternalDataSourceType.FEATUREBASE+ # unreleasedSource hides the connector from every user; a finished source must not carry it.+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/featurebase"++ fields = {f.name: f for f in config.fields}+ assert set(fields.keys()) == {"api_key"}+ api_key_field = fields["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == "password"+ assert api_key_field.required is True++ webhook_fields = {f.name: f for f in config.webhookFields or []}+ assert set(webhook_fields.keys()) == {"signing_secret"}++ def test_get_schemas_covers_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=1)+ assert [s.name for s in schemas] == list(ENDPOINTS)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["posts", "boards"])+ assert [s.name for s in schemas] == ["posts", "boards"]++ @parameterized.expand(+ [+ # Posts/comments sweep newest-first with an early cutoff; changelogs filter+ # server-side via startDate. Everything else has no time filter — full refresh only.+ ("posts", True, True),+ ("comments", True, True),+ ("changelogs", True, True),+ ("boards", False, False),+ ("post_statuses", False, False),+ ("custom_fields", False, False),+ ("admins", False, False),+ ("companies", False, False),+ ("contacts", False, False),+ ("post_voters", False, False),+ ]+ )+ def test_schema_sync_capabilities(self, endpoint: str, incremental: bool, webhooks: bool) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=1)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is incremental+ assert schema.supports_webhooks is webhooks+ # All Featurebase resources are mutable, so merge is the only safe write disposition.+ assert schema.supports_append is False++ def test_post_voters_is_off_by_default(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=1)}+ assert schemas["post_voters"].should_sync_default is False++ @parameterized.expand(+ [+ ("valid", (True, None), True, None),+ ("invalid", (False, "Invalid API Key"), False, "Invalid API Key"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, transport_result: tuple, expected_valid: bool, expected_error: str | None+ ) -> None:+ config = MagicMock(api_key="fb_test")+ with patch(f"{SOURCE_MODULE}.validate_featurebase_credentials", return_value=transport_result) as validate:+ valid, error = self.source.validate_credentials(config, team_id=1)+ validate.assert_called_once_with("fb_test")+ assert valid is expected_valid+ assert error == expected_error++ def test_non_retryable_errors_cover_featurebase_auth_statuses(self) -> None:+ errors = self.source.get_non_retryable_errors()+ # Featurebase responds 403 for invalid keys (verified live); 401 kept as a safety net.+ assert any(key.startswith("403 Client Error") for key in errors)+ assert any(key.startswith("401 Client Error") for key in errors)++ def test_resumable_source_manager_bound_to_resume_config(self) -> None:+ with patch.object(ResumableSourceManager, "__init__", return_value=None) as init:+ self.source.get_resumable_source_manager(_make_inputs())+ assert init.call_args.args[1] is FeaturebaseResumeConfig++ def test_source_for_pipeline_plumbs_incremental_inputs(self) -> None:+ config = MagicMock(api_key="fb_test")+ inputs = _make_inputs(+ schema_name="posts",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00.000Z",+ incremental_field="updatedAt",+ )+ manager = MagicMock()+ with (+ patch(f"{SOURCE_MODULE}.featurebase_source") as featurebase_source_mock,+ patch.object(FeaturebaseSource, "get_webhook_source_manager") as webhook_manager_mock,+ ):+ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = featurebase_source_mock.call_args.kwargs+ assert kwargs["api_key"] == "fb_test"+ assert kwargs["endpoint"] == "posts"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["webhook_source_manager"] is webhook_manager_mock.return_value+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"+ assert kwargs["incremental_field"] == "updatedAt"++ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:+ # A stale watermark from a previous incremental setup must not leak into a+ # full-refresh run and silently truncate the sweep.+ config = MagicMock(api_key="fb_test")+ inputs = _make_inputs(+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00.000Z",+ )+ with (+ patch(f"{SOURCE_MODULE}.featurebase_source") as featurebase_source_mock,+ patch.object(FeaturebaseSource, "get_webhook_source_manager"),+ ):+ self.source.source_for_pipeline(config, MagicMock(), inputs)++ assert featurebase_source_mock.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestFeaturebaseWebhooks:+ def setup_method(self) -> None:+ self.source = FeaturebaseSource()+ self.config = MagicMock(api_key="fb_test")++ def test_webhook_resource_map_routes_item_object_types(self) -> None:+ # Keys must be schema names from get_schemas; values must match data.item.object in+ # webhook payloads — this is what routes an event into the right warehouse table.+ assert self.source.webhook_resource_map == {+ "posts": "post",+ "comments": "comment",+ "changelogs": "changelog",+ }+ schema_names = {s.name for s in self.source.get_schemas(MagicMock(), team_id=1)}+ assert set(self.source.webhook_resource_map.keys()) <= schema_names++ def test_webhook_template_present(self) -> None:+ template = self.source.webhook_template+ assert template is not None+ assert template.id == "template-warehouse-source-featurebase"+ assert template.type == "warehouse_source_webhook"+ input_keys = {i["key"] for i in template.inputs_schema}+ assert {"signing_secret", "schema_mapping", "source_id"} <= input_keys++ def test_desired_webhook_events_only_mapped_topics(self) -> None:+ topics = self.source.get_desired_webhook_events(self.config, ["posts"]) or []+ assert set(topics) == {+ "post.created",+ "post.updated",+ "comment.created",+ "comment.updated",+ "changelog.published",+ }+ # Deleted-object topics would resurrect deleted rows through the merge path.+ assert not any(topic.endswith(".deleted") for topic in topics)++ @parameterized.expand(+ [+ ("create_webhook", "create_featurebase_webhook"),+ ("delete_webhook", "delete_featurebase_webhook"),+ ("get_external_webhook_info", "get_featurebase_webhook_info"),+ ]+ )+ def test_webhook_methods_delegate_to_transport(self, method_name: str, transport_name: str) -> None:+ with patch(f"{SOURCE_MODULE}.{transport_name}") as transport:+ result = getattr(self.source, method_name)(self.config, "https://us.posthog.com/webhook", team_id=1)+ transport.assert_called_once_with("fb_test", "https://us.posthog.com/webhook")+ assert result is transport.return_value++ def test_sync_webhook_events_passes_desired_topics(self) -> None:+ with patch(f"{SOURCE_MODULE}.sync_featurebase_webhook_events") as transport:+ self.source.sync_webhook_events(self.config, "https://us.posthog.com/webhook", 1, ["posts"])+ api_key, url, topics = transport.call_args.args+ assert api_key == "fb_test"+ assert url == "https://us.posthog.com/webhook"+ assert "changelog.published" in topicsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/webhook_template.pynew file mode 100644index 000000000000..7ad584080777--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/featurebase/webhook_template.py@@ -0,0 +1,135 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++# Featurebase signs webhooks with HMAC-SHA256 over "{timestamp}.{raw body}" using the+# whsec_ signing secret, sent as X-Webhook-Signature with X-Webhook-Timestamp (5 minute+# replay window). The payload envelope is {topic, data: {item, changes}}; data.item.object+# identifies the resource type used for schema routing.+template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-featurebase",+ name="Featurebase warehouse source webhook",+ description="Receive Featurebase webhook events for data warehouse ingestion",+ icon_url="/static/services/featurebase.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_signature_check) {+ if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Signing secret not configured',+ }+ }+ }++ let body := request.stringBody+ let signatureHeader := request.headers['x-webhook-signature']+ let timestamp := request.headers['x-webhook-timestamp']++ if (empty(signatureHeader) or empty(timestamp)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+ }++ let signedPayload := concat(timestamp, '.', body)+ let computedSignature := sha256HmacChainHex([inputs.signing_secret, signedPayload])++ if (computedSignature != signatureHeader) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+ }++ let currentTime := toInt(toUnixTimestamp(now()))+ let timestampDelta := currentTime - toInt(timestamp)+ if (timestampDelta > 300 or timestampDelta < -300) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Timestamp outside tolerance',+ }+ }+ }+}++let objectType := request.body.data?.item?.object++if (empty(objectType)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No object type found, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.[objectType]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for object type: {objectType}, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": "Used to validate the webhook came from Featurebase",+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the X-Webhook-Signature header will not be checked. This is not recommended.",+ "default": False,+ "required": False,+ "secret": False,+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Featurebase object types to ExternalDataSchema IDs",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ {+ "type": "string",+ "key": "source_id",+ "label": "Source ID",+ "description": "The ExternalDataSource ID this webhook is associated with",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ ],+)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 308f8283d19d..a6449252729e 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@@ -1504,7 +1504,7 @@ class FaunaSourceConfig(config.Config):@config.configclass FeaturebaseSourceConfig(config.Config):- pass+ api_key: str@config.config