: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 jellyfish import source (#71196)
Tom Owerscad2e2b5349d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 30cf97dd3ce3..da4803a91125 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -266,6 +266,7 @@ the row lists both.| invoiceninja | HTTP | requests | ✅ || ip2whois | HTTP | requests | ✅ || iterable | HTTP | requests | ✅ |+| jellyfish | HTTP | requests | ✅ || jira | HTTP | requests | ✅ || jobnimbus | HTTP | requests | ✅ || jotform | HTTP | requests | ✅ |@@ -731,7 +732,6 @@ doesn't conflict with concurrent PRs.- instantly- interzoid- jamf_pro-- jellyfish- jenkins- jfrog_artifactory- jobberdiff --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 7a8b0af04d35..227c06be48b7 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@@ -2188,7 +2188,7 @@ class JamfProSourceConfig(config.Config):@config.configclass JellyfishSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/canonical_descriptions.pynew file mode 100644index 000000000000..26a780c1d8d9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/canonical_descriptions.py@@ -0,0 +1,82 @@+"""Canonical descriptions for Jellyfish export endpoints.++Sourced from the official Jellyfish-AI/jellyfish-mcp wrapper's tool documentation+(https://github.com/Jellyfish-AI/jellyfish-mcp) — the full API reference lives behind the+Jellyfish app login, so column-level coverage is limited to fields documented there. Keyed by the+endpoint names in `settings.py` `JELLYFISH_ENDPOINTS`.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_WINDOW_COLUMNS = {+ "window_start_date": "First day of the calendar-month window this row was exported for (added by PostHog).",+ "window_end_date": "Last day of the calendar-month window this row was exported for (added by PostHog).",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "engineers": {+ "description": "Active allocatable people tracked in Jellyfish, as returned by the people export.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {+ "id": "Unique Jellyfish identifier for the person.",+ },+ },+ "teams": {+ "description": "The Jellyfish team hierarchy (top-level teams and their children).",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {+ "id": "Unique Jellyfish identifier for the team.",+ "name": "Display name of the team.",+ "active": "Whether the team is currently active in Jellyfish.",+ "hierarchy_level": "Depth of the team in the Jellyfish team hierarchy (1 = top level).",+ "hierarchy_level_name": "Label of the team's hierarchy level as configured in Jellyfish.",+ },+ },+ "work_categories": {+ "description": "Work categories configured in Jellyfish for grouping delivery work.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {+ "slug": "Stable identifier for the work category, used to query its contents.",+ "display_name": "Display name of the work category.",+ },+ },+ "allocations_by_person": {+ "description": "R&D allocation (FTE effort) per person for each calendar-month window.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {**_WINDOW_COLUMNS},+ },+ "allocations_by_team": {+ "description": "R&D allocation (FTE effort) per top-level team for each calendar-month window.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {**_WINDOW_COLUMNS},+ },+ "allocations_by_investment_category": {+ "description": "R&D allocation (FTE effort) per investment category for each calendar-month window.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {**_WINDOW_COLUMNS},+ },+ "company_metrics": {+ "description": "Company-wide engineering metrics (delivery and DORA-style measures) for each calendar-month window.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {**_WINDOW_COLUMNS},+ },+ "unlinked_pull_requests": {+ "description": "Pull requests Jellyfish could not link to an issue, for each calendar-month window.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {**_WINDOW_COLUMNS},+ },+ "deliverables": {+ "description": "Deliverables (epics/projects) in each Jellyfish work category, with delivery status and effort.",+ "docs_url": "https://github.com/Jellyfish-AI/jellyfish-mcp",+ "columns": {+ "work_category_slug": "Slug of the work category this deliverable was exported from (added by PostHog).",+ "name": "Display name of the deliverable.",+ "source_issue_url": "URL of the source issue (e.g. Jira epic) backing the deliverable.",+ "activity_status": "Delivery activity status of the deliverable (e.g. completed, in progress).",+ "target_date": "Target completion date for the deliverable.",+ "teams": "Teams contributing to the deliverable.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/jellyfish.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/jellyfish.pynew file mode 100644index 000000000000..efa5112f347b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/jellyfish.py@@ -0,0 +1,330 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.jellyfish.settings import (+ DEFAULT_LOOKBACK_MONTHS,+ JELLYFISH_ENDPOINTS,+ JellyfishEndpointConfig,+)++JELLYFISH_BASE_URL = "https://app.jellyfish.co/endpoints/export/v0"+# The export API has no pagination, so a whole window/list comes back in one response — allow it+# time to build.+REQUEST_TIMEOUT = 120+MAX_RETRIES = 5+# Cap the honored `Retry-After` so a pathological header can't pin an import worker for its whole+# duration; the pipeline retries the activity above us if the window is genuinely longer.+MAX_RETRY_AFTER_SECONDS = 60+# The tenacity loop below is the single retry authority — it translates 429/5xx into typed+# exceptions and backs off (honoring `Retry-After`). Adapter-level retries would nest beneath it and+# multiply the waits, so opt out of them.+_NO_ADAPTER_RETRIES = Retry(total=0)+++class JellyfishRetryableError(Exception):+ """Transient 5xx — safe to retry with backoff."""+++class JellyfishRateLimitError(Exception):+ """429 Too Many Requests. Carries the server's Retry-After (seconds) so we can honor it."""++ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class JellyfishResumeConfig:+ # Month-windowed endpoints: the ISO date of the next window to fetch. None = start from the+ # beginning of the lookback range.+ next_window_start: str | None = None+ # Fan-out endpoint (deliverables): work category slugs already fully fetched this job.+ completed_slugs: list[str] = dataclasses.field(default_factory=list)+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Token {api_token}",+ "Accept": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any]) -> str:+ base = f"{JELLYFISH_BASE_URL}/{path}"+ if not params:+ return base+ return f"{base}?{urlencode(params)}"+++def _month_windows(today: date, lookback_months: int = DEFAULT_LOOKBACK_MONTHS) -> list[tuple[date, date]]:+ """Calendar-month `[first day, last day]` windows from `lookback_months` ago through today.++ The current month's window is clipped to today. `end_date` is assumed inclusive (the API is+ not publicly documented either way); with whole-month windows an off-by-one would at most drop+ or double a single boundary day, and full-refresh syncs restate every window each run.+ """+ start = date(today.year, today.month, 1)+ months: list[date] = []+ for _ in range(lookback_months):+ months.append(start)+ start = (start - timedelta(days=1)).replace(day=1)+ months.reverse()++ windows: list[tuple[date, date]] = []+ for first_day in months:+ next_month = (first_day + timedelta(days=32)).replace(day=1)+ last_day = next_month - timedelta(days=1)+ windows.append((first_day, min(last_day, today)))+ return windows+++def _extract_rows(payload: Any, data_key: str | None = None) -> list[dict[str, Any]]:+ """Pull the row list out of a response whose exact wrapping isn't publicly documented.++ Known shapes are handled first (`data_key`, bare list); otherwise a dict with exactly one+ list-of-dicts value unwraps to that list, and anything else is kept whole as a single row+ rather than guessed at.+ """+ if isinstance(payload, list):+ return [row for row in payload if isinstance(row, dict)]++ if isinstance(payload, dict):+ if data_key is not None:+ wrapped = payload.get(data_key)+ if isinstance(wrapped, list):+ return [row for row in wrapped if isinstance(row, dict)]++ list_values = [+ value+ for value in payload.values()+ if isinstance(value, list) and value and all(isinstance(item, dict) for item in value)+ ]+ if len(list_values) == 1:+ return list_values[0]++ return [payload]++ return []+++def _parse_retry_after(value: str | None) -> float | None:+ if not value:+ return None+ try:+ seconds = float(value)+ except ValueError:+ return None+ # A negative (or non-numeric) value is meaningless as a wait, so fall back to exponential backoff.+ return seconds if seconds >= 0 else None+++def _retry_wait(retry_state: Any) -> float:+ """Honor a 429's Retry-After header when present (capped), else fall back to exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, JellyfishRateLimitError) and exc.retry_after is not None:+ return min(exc.retry_after, MAX_RETRY_AFTER_SECONDS)+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++@retry(+ retry=retry_if_exception_type(+ (JellyfishRetryableError, JellyfishRateLimitError, requests.ReadTimeout, requests.ConnectionError)+ ),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+)+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT)++ if response.status_code == 429:+ raise JellyfishRateLimitError(+ f"Jellyfish API rate limited: url={url}",+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),+ )++ if response.status_code >= 500:+ raise JellyfishRetryableError(f"Jellyfish API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Jellyfish API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_token: str) -> bool:+ # `delivery/work_categories` is the cheapest export endpoint (a short reference list, no+ # required params). Jellyfish returns 403 for both missing and invalid tokens (verified live),+ # so any non-200 means the token isn't usable.+ url = _build_url("delivery/work_categories", {"format": "json"})+ try:+ session = make_tracked_session(retry=_NO_ADAPTER_RETRIES)+ response = session.get(url, headers=_get_headers(api_token), timeout=30)+ return response.status_code == 200+ except Exception:+ return False+++def _list_work_category_slugs(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[str]:+ payload = _fetch(session, _build_url("delivery/work_categories", {"format": "json"}), headers, logger)+ rows = _extract_rows(payload)+ slugs: list[str] = []+ for row in rows:+ # Work category rows carry a slug/id (the field name isn't publicly documented; `slug` is+ # what `work_category_slug` params take, so prefer it).+ slug = row.get("slug") or row.get("work_category_slug") or row.get("id")+ if slug is not None:+ slugs.append(str(slug))+ if not slugs and rows:+ logger.error(f"Jellyfish: could not find a slug field in work_categories rows: keys={sorted(rows[0])}")+ return slugs+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JellyfishResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = JELLYFISH_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ session = make_tracked_session(retry=_NO_ADAPTER_RETRIES)++ # The export API returns CSV unless asked otherwise, so `format=json` goes on every request.+ base_params: dict[str, Any] = {"format": "json", **config.params}++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ today = datetime.now(UTC).date()++ if config.window_mode == "month":+ yield from _get_month_windowed_rows(+ session, headers, logger, config, base_params, resumable_source_manager, resume, today+ )+ elif config.fan_out_slug_param is not None:+ yield from _get_fan_out_rows(+ session, headers, logger, config, base_params, resumable_source_manager, resume, today+ )+ else:+ payload = _fetch(session, _build_url(config.path, base_params), headers, logger)+ rows = _extract_rows(payload, config.data_key)+ if rows:+ yield rows+++def _get_month_windowed_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: JellyfishEndpointConfig,+ base_params: dict[str, Any],+ resumable_source_manager: ResumableSourceManager[JellyfishResumeConfig],+ resume: JellyfishResumeConfig | None,+ today: date,+) -> Iterator[list[dict[str, Any]]]:+ windows = _month_windows(today)+ if resume is not None and resume.next_window_start:+ windows = [w for w in windows if w[0].isoformat() >= resume.next_window_start]+ logger.debug(f"Jellyfish: resuming {config.name} from window {resume.next_window_start}")++ for index, (window_start, window_end) in enumerate(windows):+ params = {+ **base_params,+ "start_date": window_start.isoformat(),+ "end_date": window_end.isoformat(),+ "unit": "month",+ }+ payload = _fetch(session, _build_url(config.path, params), headers, logger)+ rows = _extract_rows(payload, config.data_key)+ for row in rows:+ # Stamp the requested window so per-period aggregates keep their period (and give the+ # table its stable partition key).+ row.setdefault("window_start_date", window_start.isoformat())+ row.setdefault("window_end_date", window_end.isoformat())+ if rows:+ yield rows++ # Save AFTER yielding so a crash re-fetches this window instead of skipping it.+ if index + 1 < len(windows):+ resumable_source_manager.save_state(+ JellyfishResumeConfig(next_window_start=windows[index + 1][0].isoformat())+ )+++def _get_fan_out_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: JellyfishEndpointConfig,+ base_params: dict[str, Any],+ resumable_source_manager: ResumableSourceManager[JellyfishResumeConfig],+ resume: JellyfishResumeConfig | None,+ today: date,+) -> Iterator[list[dict[str, Any]]]:+ slugs = _list_work_category_slugs(session, headers, logger)+ completed = set(resume.completed_slugs) if resume is not None else set()+ if completed:+ logger.debug(f"Jellyfish: resuming {config.name}, skipping {len(completed)} completed work categories")++ # Deliverables are discrete records, so one wide window over the whole lookback range per work+ # category (rather than per-month slices) fetches each deliverable once.+ window_start = _month_windows(today)[0][0]++ for slug in slugs:+ if slug in completed:+ continue+ assert config.fan_out_slug_param is not None+ params = {+ **base_params,+ config.fan_out_slug_param: slug,+ "start_date": window_start.isoformat(),+ "end_date": today.isoformat(),+ }+ payload = _fetch(session, _build_url(config.path, params), headers, logger)+ rows = _extract_rows(payload, config.data_key)+ for row in rows:+ row.setdefault("work_category_slug", slug)+ if rows:+ yield rows++ completed.add(slug)+ resumable_source_manager.save_state(JellyfishResumeConfig(completed_slugs=sorted(completed)))+++def jellyfish_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JellyfishResumeConfig],+) -> SourceResponse:+ config = JELLYFISH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ 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,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/settings.pynew file mode 100644index 000000000000..06769308f7e0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/settings.py@@ -0,0 +1,101 @@+from dataclasses import dataclass, field+from typing import Any, Literal, Optional++# How far back the windowed analytics endpoints sync. The export API has no pagination — data is+# scoped purely by `start_date`/`end_date` windows — so every sync walks this many month windows.+# Rows are small monthly aggregates, so two years stays cheap (one request per month per endpoint).+DEFAULT_LOOKBACK_MONTHS = 24++# `window_mode` controls how an endpoint is scoped by date:+# - "month": one request per calendar-month window (aggregate/metric endpoints); rows get+# `window_start_date` / `window_end_date` injected so each aggregate keeps its period.+# - "full": a single request covering the whole lookback range (entity-shaped rows like+# deliverables, where a wide window returns discrete records, not per-period aggregates).+# - None: no date params (small reference lists).+WindowMode = Optional[Literal["month", "full"]]+++@dataclass+class JellyfishEndpointConfig:+ name: str+ path: str # relative to https://app.jellyfish.co/endpoints/export/v0/+ window_mode: WindowMode = None+ # Static query params the endpoint requires (beyond auth/format/date windows).+ params: dict[str, Any] = field(default_factory=dict)+ # Top-level response key wrapping the row list, when known (e.g. `deliverables`). The row+ # extractor falls back to auto-detecting a single list-of-dicts value when this is unset.+ data_key: str | None = None+ # When set, the endpoint is called once per work category: slugs are listed from+ # `delivery/work_categories` and passed via this query param.+ fan_out_slug_param: str | None = None+ primary_keys: list[str] | None = None+ # Only month-windowed endpoints partition — on the injected, stable `window_start_date`.+ partition_key: str | None = None+++# The endpoints a Jellyfish user actually wants in a warehouse, cross-referenced against the+# official Jellyfish-AI/jellyfish-mcp wrapper (no Airbyte/Fivetran connector exists): reference+# lists (engineers, teams, work categories), R&D allocation breakdowns, delivery deliverables, and+# company-level metrics. Endpoints requiring per-entity ids (person/team metrics, scope history)+# are deliberately left out of v1 — they need fan-out over volatile id lists.+JELLYFISH_ENDPOINTS: dict[str, JellyfishEndpointConfig] = {+ "engineers": JellyfishEndpointConfig(+ name="engineers",+ path="people/list_engineers",+ primary_keys=["id"],+ ),+ "teams": JellyfishEndpointConfig(+ name="teams",+ path="teams/list_teams",+ # `hierarchy_level` is required; level 1 + include_children walks the whole team tree.+ params={"hierarchy_level": 1, "include_children": "true"},+ data_key="teams",+ primary_keys=["id"],+ ),+ "work_categories": JellyfishEndpointConfig(+ name="work_categories",+ path="delivery/work_categories",+ primary_keys=["slug"],+ ),+ "allocations_by_person": JellyfishEndpointConfig(+ name="allocations_by_person",+ path="allocations/details/by_person",+ window_mode="month",+ partition_key="window_start_date",+ ),+ "allocations_by_team": JellyfishEndpointConfig(+ name="allocations_by_team",+ path="allocations/details/by_team",+ # `team_hierarchy_level` is required; 1 is the top organizational level.+ params={"team_hierarchy_level": 1},+ window_mode="month",+ partition_key="window_start_date",+ ),+ "allocations_by_investment_category": JellyfishEndpointConfig(+ name="allocations_by_investment_category",+ path="allocations/details/investment_category",+ window_mode="month",+ partition_key="window_start_date",+ ),+ "company_metrics": JellyfishEndpointConfig(+ name="company_metrics",+ path="metrics/company_metrics",+ window_mode="month",+ partition_key="window_start_date",+ ),+ "unlinked_pull_requests": JellyfishEndpointConfig(+ name="unlinked_pull_requests",+ path="metrics/unlinked_pull_requests",+ window_mode="month",+ partition_key="window_start_date",+ ),+ "deliverables": JellyfishEndpointConfig(+ name="deliverables",+ path="delivery/work_category_contents",+ window_mode="full",+ data_key="deliverables",+ fan_out_slug_param="work_category_slug",+ ),+}++ENDPOINTS = tuple(JELLYFISH_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/source.pyindex 5b3284508284..ad703f6f30a2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/source.py@@ -1,19 +1,39 @@-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import JellyfishSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.jellyfish import (+ JellyfishResumeConfig,+ jellyfish_source,+ validate_credentials as validate_jellyfish_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.settings import ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class JellyfishSource(SimpleSource[JellyfishSourceConfig]):+class JellyfishSource(ResumableSource[JellyfishSourceConfig, JellyfishResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.JELLYFISH@@ -23,8 +43,90 @@ class JellyfishSource(SimpleSource[JellyfishSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.JELLYFISH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Jellyfish (Jellyfish Software, Inc.)",+ label="Jellyfish",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Jellyfish API token to pull your engineering-intelligence data (R&D allocations, delivery deliverables, engineering metrics, engineers, and teams) into the PostHog Data warehouse.++Generate a token in Jellyfish under **Settings → Data Connections → API Export** (requires the API Export feature on your plan and an Admin user role). Note that Jellyfish tokens are created with an expiry — reconnect with a fresh token when yours expires.""",iconPath="/static/services/jellyfish.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/jellyfish",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Jellyfish returns 403 for both missing and invalid/expired tokens (verified live); 401 is+ # covered in case that ever changes. Retrying can never satisfy a credential problem.+ return {+ "401 Client Error: Unauthorized for url: https://app.jellyfish.co": "Your Jellyfish API token is invalid or has expired. Generate a new token under Settings → Data Connections → API Export in Jellyfish, then reconnect.",+ "403 Client Error: Forbidden for url: https://app.jellyfish.co": "Your Jellyfish API token is invalid or has expired. Generate a new token under Settings → Data Connections → API Export in Jellyfish, then reconnect.",+ }++ def get_schemas(+ self,+ config: JellyfishSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full-refresh: the export API filters by date window rather than an+ # updated-since cursor, and windowed aggregates can be restated, so each sync rebuilds the+ # (small) tables from the whole lookback range.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: JellyfishSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_jellyfish_credentials(config.api_token):+ return True, None++ return False, "Invalid Jellyfish API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JellyfishResumeConfig]:+ return ResumableSourceManager[JellyfishResumeConfig](inputs, JellyfishResumeConfig)++ def source_for_pipeline(+ self,+ config: JellyfishSourceConfig,+ resumable_source_manager: ResumableSourceManager[JellyfishResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return jellyfish_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/tests/test_jellyfish.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/tests/test_jellyfish.pynew file mode 100644index 000000000000..8d82598ea492--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/tests/test_jellyfish.py@@ -0,0 +1,283 @@+from datetime import date+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish import jellyfish+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.jellyfish import (+ MAX_RETRY_AFTER_SECONDS,+ JellyfishRateLimitError,+ JellyfishResumeConfig,+ _build_url,+ _extract_rows,+ _get_headers,+ _month_windows,+ _parse_retry_after,+ _retry_wait,+ get_rows,+ jellyfish_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.settings import JELLYFISH_ENDPOINTS+++class TestHeaders:+ def test_uses_token_auth_scheme(self) -> None:+ # Jellyfish uses `Token <token>` (verified against the live API), not `Bearer`.+ assert _get_headers("abc")["Authorization"] == "Token abc"+++class TestMonthWindows:+ def test_windows_cover_lookback_and_clip_current_month_to_today(self) -> None:+ windows = _month_windows(date(2026, 3, 10), lookback_months=24)+ assert len(windows) == 24+ assert windows[0] == (date(2024, 4, 1), date(2024, 4, 30))+ # Complete months span first through last day (no gaps or overlaps at boundaries).+ assert windows[-2] == (date(2026, 2, 1), date(2026, 2, 28))+ # The in-progress month never asks for future dates.+ assert windows[-1] == (date(2026, 3, 1), date(2026, 3, 10))++ def test_first_of_month_today_produces_single_day_window(self) -> None:+ windows = _month_windows(date(2026, 3, 1), lookback_months=2)+ assert windows[-1] == (date(2026, 3, 1), date(2026, 3, 1))+++class TestExtractRows:+ @parameterized.expand(+ [+ ("bare_list", [{"id": 1}, {"id": 2}], None, [{"id": 1}, {"id": 2}]),+ ("bare_list_drops_non_dicts", [{"id": 1}, "junk"], None, [{"id": 1}]),+ ("known_data_key", {"deliverables": [{"id": 1}], "meta": {"x": 1}}, "deliverables", [{"id": 1}]),+ ("single_list_value_autodetected", {"teams": [{"id": 7}]}, None, [{"id": 7}]),+ ("scalar_payload", "not json rows", None, []),+ ]+ )+ def test_extract(self, _name: str, payload: Any, data_key: str | None, expected: list[dict]) -> None:+ assert _extract_rows(payload, data_key) == expected++ def test_ambiguous_dict_is_kept_whole_as_one_row(self) -> None:+ # Two list-of-dict values means we can't tell which holds the rows — keep the payload+ # intact rather than guessing and silently dropping half the data.+ payload = {"a": [{"x": 1}], "b": [{"y": 2}]}+ assert _extract_rows(payload) == [payload]++ def test_missing_data_key_falls_back_to_autodetection(self) -> None:+ assert _extract_rows({"items": [{"id": 1}]}, data_key="deliverables") == [{"id": 1}]+++class _FakeResumableManager:+ def __init__(self, state: JellyfishResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[JellyfishResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> JellyfishResumeConfig | None:+ return self._state++ def save_state(self, data: JellyfishResumeConfig) -> None:+ self.saved.append(data)+++def _install_fake_fetch(monkeypatch: Any, responder: Any) -> list[dict[str, Any]]:+ """Route `_fetch` to `responder(path, params)`; returns the list of captured requests."""+ calls: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ parsed = urlparse(url)+ params = {k: v[0] if len(v) == 1 else v for k, v in parse_qs(parsed.query).items()}+ path = parsed.path.removeprefix("/endpoints/export/v0/")+ calls.append({"path": path, "params": params})+ return responder(path, params)++ monkeypatch.setattr(jellyfish, "_fetch", fake_fetch)+ return calls+++def _collect(endpoint: str, manager: _FakeResumableManager, today: date, monkeypatch: Any) -> list[dict]:+ class _FixedDatetime:+ @staticmethod+ def now(tz: Any = None) -> Any:+ return MagicMock(date=lambda: today)++ monkeypatch.setattr(jellyfish, "datetime", _FixedDatetime)++ rows: list[dict] = []+ for batch in get_rows(+ api_token="t",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestGetRowsReference:+ def test_single_request_with_static_params_and_json_format(self, monkeypatch: Any) -> None:+ calls = _install_fake_fetch(monkeypatch, lambda path, params: {"teams": [{"id": 7, "name": "Core"}]})+ rows = _collect("teams", _FakeResumableManager(), date(2026, 3, 10), monkeypatch)++ assert rows == [{"id": 7, "name": "Core"}]+ assert calls == [+ {+ "path": "teams/list_teams",+ # `format=json` is mandatory (the API otherwise defaults to CSV); hierarchy params+ # are what makes list_teams return the whole tree.+ "params": {"format": "json", "hierarchy_level": "1", "include_children": "true"},+ }+ ]+++class TestGetRowsMonthWindowed:+ def test_walks_every_window_injects_window_fields_and_saves_state_after_yield(self, monkeypatch: Any) -> None:+ calls = _install_fake_fetch(monkeypatch, lambda path, params: [{"metric": "x"}])+ manager = _FakeResumableManager()+ rows = _collect("company_metrics", manager, date(2026, 3, 10), monkeypatch)++ assert len(calls) == 24+ assert all(c["path"] == "metrics/company_metrics" for c in calls)+ assert calls[0]["params"]["start_date"] == "2024-04-01"+ assert calls[0]["params"]["end_date"] == "2024-04-30"+ assert calls[0]["params"]["unit"] == "month"+ assert calls[-1]["params"] == {+ "format": "json",+ "start_date": "2026-03-01",+ "end_date": "2026-03-10",+ "unit": "month",+ }+ # Each aggregate row keeps its period.+ assert rows[0] == {"metric": "x", "window_start_date": "2024-04-01", "window_end_date": "2024-04-30"}+ assert rows[-1]["window_start_date"] == "2026-03-01"+ # State points at the NEXT window and is saved after each yielded window except the last —+ # a crash re-fetches the current window instead of skipping it.+ assert len(manager.saved) == 23+ assert manager.saved[0] == JellyfishResumeConfig(next_window_start="2024-05-01")+ assert manager.saved[-1] == JellyfishResumeConfig(next_window_start="2026-03-01")++ def test_resume_skips_windows_before_saved_watermark(self, monkeypatch: Any) -> None:+ calls = _install_fake_fetch(monkeypatch, lambda path, params: [{"metric": "x"}])+ manager = _FakeResumableManager(JellyfishResumeConfig(next_window_start="2026-02-01"))+ _collect("company_metrics", manager, date(2026, 3, 10), monkeypatch)++ assert [c["params"]["start_date"] for c in calls] == ["2026-02-01", "2026-03-01"]+++class TestGetRowsFanOut:+ @staticmethod+ def _responder(path: str, params: dict[str, Any]) -> Any:+ if path == "delivery/work_categories":+ return [{"slug": "roadmap"}, {"slug": "kt"}]+ assert path == "delivery/work_category_contents"+ return {"deliverables": [{"name": f"deliverable-{params['work_category_slug']}"}]}++ def test_fans_out_per_work_category_and_injects_slug(self, monkeypatch: Any) -> None:+ calls = _install_fake_fetch(monkeypatch, self._responder)+ manager = _FakeResumableManager()+ rows = _collect("deliverables", manager, date(2026, 3, 10), monkeypatch)++ assert rows == [+ {"name": "deliverable-roadmap", "work_category_slug": "roadmap"},+ {"name": "deliverable-kt", "work_category_slug": "kt"},+ ]+ content_calls = [c for c in calls if c["path"] == "delivery/work_category_contents"]+ # One wide window over the whole lookback range — deliverables are discrete records, not+ # per-period aggregates.+ assert content_calls[0]["params"]["start_date"] == "2024-04-01"+ assert content_calls[0]["params"]["end_date"] == "2026-03-10"+ assert manager.saved == [+ JellyfishResumeConfig(completed_slugs=["roadmap"]),+ JellyfishResumeConfig(completed_slugs=["kt", "roadmap"]),+ ]++ def test_resume_skips_completed_work_categories(self, monkeypatch: Any) -> None:+ calls = _install_fake_fetch(monkeypatch, self._responder)+ manager = _FakeResumableManager(JellyfishResumeConfig(completed_slugs=["roadmap"]))+ rows = _collect("deliverables", manager, date(2026, 3, 10), monkeypatch)++ assert [r["work_category_slug"] for r in rows] == ["kt"]+ content_slugs = [+ c["params"]["work_category_slug"] for c in calls if c["path"] == "delivery/work_category_contents"+ ]+ assert content_slugs == ["kt"]++ def test_work_category_rows_without_slug_fall_back_to_id(self, monkeypatch: Any) -> None:+ def responder(path: str, params: dict[str, Any]) -> Any:+ if path == "delivery/work_categories":+ return [{"id": 42, "display_name": "Roadmap"}]+ return {"deliverables": [{"name": "d"}]}++ calls = _install_fake_fetch(monkeypatch, responder)+ _collect("deliverables", _FakeResumableManager(), date(2026, 3, 10), monkeypatch)+ content_calls = [c for c in calls if c["path"] == "delivery/work_category_contents"]+ assert content_calls[0]["params"]["work_category_slug"] == "42"+++class TestJellyfishSourceResponse:+ def test_windowed_endpoint_partitions_on_injected_window_start(self) -> None:+ response = jellyfish_source("t", "company_metrics", MagicMock(), MagicMock())+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == ["window_start_date"]++ def test_reference_endpoint_has_primary_key_and_no_partitioning(self) -> None:+ response = jellyfish_source("t", "engineers", MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None++ def test_every_declared_endpoint_builds_a_response(self) -> None:+ for endpoint in JELLYFISH_ENDPOINTS:+ assert jellyfish_source("t", endpoint, MagicMock(), MagicMock()).name == endpoint+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code,expected", [(200, True), (401, False), (403, False)])+ def test_status_maps_to_bool(self, status_code: int, expected: bool, monkeypatch: Any) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ monkeypatch.setattr(jellyfish, "make_tracked_session", lambda *a, **k: session)+ assert validate_credentials("t") is expected++ def test_network_error_is_not_valid(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ monkeypatch.setattr(jellyfish, "make_tracked_session", lambda *a, **k: session)+ assert validate_credentials("t") is False+++class TestFetch:+ def test_429_raises_rate_limit_with_retry_after(self) -> None:+ response = MagicMock()+ response.status_code = 429+ response.headers = {"Retry-After": "12"}+ session = MagicMock()+ session.get.return_value = response+ # Call the undecorated body (bypassing tenacity) to assert the error carries Retry-After.+ with pytest.raises(JellyfishRateLimitError) as exc:+ jellyfish._fetch.__wrapped__(session, _build_url("metrics/company_metrics", {}), {}, MagicMock()) # type: ignore[attr-defined]+ assert exc.value.retry_after == 12.0+++class TestRetryWait:+ @parameterized.expand([("missing", None, None), ("non_numeric", "soon", None), ("negative", "-5", None)])+ def test_parse_retry_after_falls_back(self, _name: str, header: str | None, expected: float | None) -> None:+ # None means "no honored delay" so the caller falls back to exponential backoff.+ assert _parse_retry_after(header) == expected++ def test_wait_honors_retry_after_when_reasonable(self) -> None:+ state = MagicMock()+ state.outcome.exception.return_value = JellyfishRateLimitError("rate limited", retry_after=12.0)+ assert _retry_wait(state) == 12.0++ def test_wait_clamps_pathological_retry_after(self) -> None:+ # A huge Retry-After must not pin an import worker for its whole duration.+ state = MagicMock()+ state.outcome.exception.return_value = JellyfishRateLimitError("rate limited", retry_after=6000.0)+ assert _retry_wait(state) == MAX_RETRY_AFTER_SECONDSdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/tests/test_jellyfish_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/tests/test_jellyfish_source.pynew file mode 100644index 000000000000..1fe9f0e5e642--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jellyfish/tests/test_jellyfish_source.py@@ -0,0 +1,126 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import JellyfishSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.jellyfish import JellyfishResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.jellyfish.source import JellyfishSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestJellyfishSource:+ def setup_method(self) -> None:+ self.source = JellyfishSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.JELLYFISH++ def test_config_fields(self) -> None:+ config = self.source.get_source_config+ fields = {f.name: f for f in config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"api_token"}+ assert fields["api_token"].required is True+ assert fields["api_token"].secret is True++ def test_source_is_released(self) -> None:+ # `unreleasedSource=True` hides the connector from every user — a finished source must+ # never carry it (newness is expressed via releaseStatus instead).+ config = self.source.get_source_config+ assert not config.unreleasedSource+ assert config.releaseStatus is not None++ def test_docs_url_matches_doc_filename(self) -> None:+ assert self.source.get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/jellyfish"++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_every_endpoint_full_refresh_only(self) -> None:+ # The export API has no updated-since cursor and its date filters couldn't be verified+ # against a live account, so no endpoint may advertise incremental sync.+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}+ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["engineers"])+ assert [s.name for s in schemas] == ["engineers"]++ def test_documented_tables_render_from_static_catalog(self) -> None:+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert tables["engineers"]["description"]+ assert tables["engineers"]["sync_methods"] == ["Full refresh"]++ @pytest.mark.parametrize("probe_result,expected_valid", [(True, True), (False, False)])+ def test_validate_credentials(self, probe_result: bool, expected_valid: bool, monkeypatch: Any) -> None:+ monkeypatch.setattr(source_module, "validate_jellyfish_credentials", lambda api_token: probe_result)+ config = JellyfishSourceConfig(api_token="t")+ valid, error = self.source.validate_credentials(config, self.team_id)+ assert valid is expected_valid+ assert (error is None) is expected_valid++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://app.jellyfish.co/endpoints/export/v0/people/list_engineers",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://app.jellyfish.co/endpoints/export/v0/metrics/company_metrics",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("timeout", "HTTPSConnectionPool(host='app.jellyfish.co', port=443): Read timed out."),+ ("server_error", "500 Server Error for url: https://app.jellyfish.co/endpoints/export/v0/teams/list_teams"),+ ("rate_limit", "429 Too Many Requests"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_resumable_manager_is_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is JellyfishResumeConfig++ def test_source_for_pipeline_plumbs_args(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_jellyfish_source(**kwargs: Any) -> str:+ captured.update(kwargs)+ return "response"++ monkeypatch.setattr(source_module, "jellyfish_source", fake_jellyfish_source)++ config = JellyfishSourceConfig(api_token="my-token")+ manager = MagicMock()+ inputs = MagicMock()+ inputs.schema_name = "engineers"++ result: Any = self.source.source_for_pipeline(config, manager, inputs)++ assert result == "response"+ assert captured["api_token"] == "my-token"+ assert captured["endpoint"] == "engineers"+ assert captured["resumable_source_manager"] is manager