Skip to content

: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.

feat(data-warehouse): add FRED source (#77146)

Tom Owers7f402cc73ebe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 255c09d3e764..91cd48d647d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -268,6 +268,7 @@ the row lists both.
| flowlu | HTTP | requests | ✅ |
| fly_io | HTTP | requests | ✅ |
| formbricks | HTTP | requests | ✅ |
+| fred | HTTP | requests | ✅ |
| frill | HTTP | requests | ✅ |
| front | HTTP | requests | ✅ |
| fulcrum | HTTP | requests | ✅ |
@@ -955,6 +956,7 @@ doesn't conflict with concurrent PRs.
- fly_io
- formbricks
- fortnox
+- fourthwall
- fred
- freeagent
- freightview
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fred/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/canonical_descriptions.py
new file mode 100644
index 000000000000..428299344b02
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/canonical_descriptions.py
@@ -0,0 +1,119 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+DOCS_BASE_URL = "https://fred.stlouisfed.org/docs/api/fred"
+
+# Shared across every table: FRED versions each record over a real-time (ALFRED) period, so
+# each row carries the window during which it was the current version of that record.
+_REALTIME_COLUMNS = {
+ "realtime_start": "Start of the real-time period this version of the record was in effect for.",
+ "realtime_end": "End of the real-time period this version of the record was in effect for. 9999-12-31 for the current version.",
+}
+
+_TAG_COLUMNS = {
+ "name": "Tag name, for example 'usa', 'monthly' or 'nsa'.",
+ "group_id": "Group the tag belongs to: freq (frequency), gen (general), geo (geography), geot (geography type), rls (release), seas (seasonal adjustment) or src (source).",
+ "notes": "Description of the tag.",
+ "created": "Timestamp of when the tag was created.",
+ "popularity": "FRED popularity score for the tag, from 0 to 100.",
+ "series_count": "Number of series carrying the tag.",
+}
+
+_RELEASE_COLUMNS = {
+ "id": "Numeric identifier for the release.",
+ "name": "Name of the release, for example 'Employment Situation'.",
+ "press_release": "True when the release has an accompanying press release.",
+ "link": "URL of the release on the publishing agency's site.",
+ "notes": "Description of the release.",
+ **_REALTIME_COLUMNS,
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "series": {
+ "description": "Metadata for each economic data series listed in the source's series IDs, including its title, frequency, units and when it was last updated.",
+ "docs_url": f"{DOCS_BASE_URL}/series.html",
+ "columns": {
+ "id": "FRED series ID, for example UNRATE or CPIAUCSL.",
+ "title": "Title of the series, for example 'Unemployment Rate'.",
+ "observation_start": "Date of the earliest observation available for the series.",
+ "observation_end": "Date of the most recent observation available for the series.",
+ "frequency": "Native frequency of the series, for example 'Monthly' or 'Quarterly'.",
+ "frequency_short": "Short code for the native frequency, for example 'M' or 'Q'.",
+ "units": "Units the observation values are expressed in, for example 'Percent'.",
+ "units_short": "Short form of the units.",
+ "seasonal_adjustment": "Seasonal adjustment applied to the series, for example 'Seasonally Adjusted'.",
+ "seasonal_adjustment_short": "Short code for the seasonal adjustment, for example 'SA' or 'NSA'.",
+ "last_updated": "Timestamp of when FRED last updated the series, in US Central time.",
+ "popularity": "FRED popularity score for the series, from 0 to 100.",
+ "notes": "Description of the series, usually including its source and methodology.",
+ **_REALTIME_COLUMNS,
+ },
+ },
+ "observations": {
+ "description": "Observation values over time for each series in the source's series IDs. One row per series and observation date.",
+ "docs_url": f"{DOCS_BASE_URL}/series_observations.html",
+ "columns": {
+ "series_id": "FRED series ID the observation belongs to, taken from the source's series IDs.",
+ "date": "Date the observation refers to.",
+ "value": "Observed value, as a string. FRED returns '.' when no value is available for that date.",
+ **_REALTIME_COLUMNS,
+ },
+ },
+ "series_categories": {
+ "description": "Categories each series in the source's series IDs belongs to, in FRED's category tree.",
+ "docs_url": f"{DOCS_BASE_URL}/series_categories.html",
+ "columns": {
+ "series_id": "FRED series ID the category applies to.",
+ "id": "Numeric identifier for the category.",
+ "name": "Name of the category.",
+ "parent_id": "Identifier of the parent category, or 0 at the root.",
+ },
+ },
+ "series_tags": {
+ "description": "Tags attached to each series in the source's series IDs, covering frequency, geography, source and seasonal adjustment.",
+ "docs_url": f"{DOCS_BASE_URL}/series_tags.html",
+ "columns": {
+ "series_id": "FRED series ID the tag applies to.",
+ **_TAG_COLUMNS,
+ },
+ },
+ "series_releases": {
+ "description": "The release each series in the source's series IDs is published in.",
+ "docs_url": f"{DOCS_BASE_URL}/series_release.html",
+ "columns": {
+ "series_id": "FRED series ID the release applies to.",
+ **_RELEASE_COLUMNS,
+ },
+ },
+ "releases": {
+ "description": "Every release of economic data published on FRED, such as the Employment Situation or the Consumer Price Index.",
+ "docs_url": f"{DOCS_BASE_URL}/releases.html",
+ "columns": _RELEASE_COLUMNS,
+ },
+ "release_dates": {
+ "description": "The publication calendar for FRED releases, including scheduled future dates.",
+ "docs_url": f"{DOCS_BASE_URL}/releases_dates.html",
+ "columns": {
+ "release_id": "Identifier of the release the date belongs to.",
+ "release_name": "Name of the release.",
+ "date": "Date the release was or will be published.",
+ },
+ },
+ "sources": {
+ "description": "Organizations that publish the data behind FRED releases, such as the Bureau of Labor Statistics.",
+ "docs_url": f"{DOCS_BASE_URL}/sources.html",
+ "columns": {
+ "id": "Numeric identifier for the source.",
+ "name": "Name of the publishing organization.",
+ "link": "URL of the organization's site.",
+ "notes": "Description of the source.",
+ **_REALTIME_COLUMNS,
+ },
+ },
+ "tags": {
+ "description": "Every tag FRED assigns to series, used to filter and group them by frequency, geography, publisher and seasonal adjustment.",
+ "docs_url": f"{DOCS_BASE_URL}/tags.html",
+ "columns": _TAG_COLUMNS,
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fred/fred.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/fred.py
new file mode 100644
index 000000000000..e6e1f02a67f6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/fred.py
@@ -0,0 +1,257 @@
+import re
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+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.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.settings import (
+ FRED_ENDPOINTS,
+ FredEndpointConfig,
+)
+
+# FRED is a single global deployment with no tenant subdomain and no version segment: the
+# `/fred/v2/` family added in late 2025 only covers release-level bulk observations, which
+# this source doesn't use.
+FRED_BASE_URL = "https://api.stlouisfed.org/fred"
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Series ids are pasted by hand, so accept commas, semicolons and newlines as separators.
+SERIES_ID_SEPARATOR = re.compile(r"[\s,;]+")
+SERIES_ID_PATTERN = re.compile(r"^[A-Za-z0-9._-]+$")
+
+
+class FredResumeConfig:
+ # Position in the source's series list. Always 0 for endpoints that don't fan out.
+ series_index: int = 0
+ offset: int = 0
+
+
+class FredApiError(Exception):
+ pass
+
+
+class FredAuthenticationError(FredApiError):
+ pass
+
+
+class FredRequestError(FredApiError):
+ """A rejected request that retrying cannot fix — an unknown series id, a bad param."""
+
+
+def parse_series_ids(raw: str) -> list[str]:
+ """Split the source's series-id field into an ordered, de-duplicated list.
+
+ Case is preserved rather than normalized: FRED's own ids are uppercase, but nothing in
+ the docs promises the API folds case, and a silent rewrite would make the `series_id`
+ column disagree with what the user typed.
+ """
+ series_ids: dict[str, None] = {}
+ for token in SERIES_ID_SEPARATOR.split(raw or ""):
+ cleaned = token.strip()
+ if cleaned:
+ series_ids.setdefault(cleaned, None)
+ return list(series_ids)
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ clean_params = {key: value for key, value in params.items() if value is not None}
+ return f"{FRED_BASE_URL}{path}?{urlencode(clean_params)}"
+
+
+def _error_message(response: requests.Response) -> str:
+ try:
+ body = response.json()
+ except ValueError:
+ return ""
+ if isinstance(body, dict):
+ return str(body.get("error_message") or "")
+ return ""
+
+
+def _raise_for_status(response: requests.Response, path: str) -> None:
+ if response.ok:
+ return
+
+ # FRED carries the api_key in the query string, so the URL never goes into an exception
+ # message — `requests.raise_for_status()` would put the whole thing there.
+ detail = _error_message(response)
+
+ if response.status_code in (401, 403) or (response.status_code == 400 and "api_key" in detail):
+ raise FredAuthenticationError(f"FRED authentication failed: {detail}")
+
+ if response.status_code == 400:
+ raise FredRequestError(f"FRED rejected the request (path={path}): {detail}")
+
+ raise FredApiError(f"FRED API error: status={response.status_code}, path={path}, message={detail}")
+
+
+def _fetch(session: requests.Session, api_key: str, path: str, params: dict[str, Any]) -> dict[str, Any]:
+ url = _build_url(path, {**params, "api_key": api_key, "file_type": "json"})
+ try:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ except requests.RequestException as error:
+ # A connection or timeout failure carries the prepared URL — and therefore the
+ # api_key query param — in its own message. The tracked session only redacts its
+ # telemetry, so letting this escape unchanged would write the key into job logs and
+ # into `latest_error`, where any project member viewing a failed import could read
+ # it back. Rebuild the failure from non-sensitive fields only, and suppress the
+ # original with `from None` so the chained message can't leak it either. The
+ # exception class name keeps the useful part (DNS vs TLS vs read timeout).
+ raise FredApiError(f"FRED transport error: {type(error).__name__}, path={path}") from None
+ _raise_for_status(response, path)
+ body = response.json()
+ return body if isinstance(body, dict) else {}
+
+
+def _extract_rows(
+ payload: dict[str, Any], config: FredEndpointConfig, series_id: Optional[str]
+) -> list[dict[str, Any]]:
+ rows = [row for row in (payload.get(config.data_key) or []) if isinstance(row, dict)]
+ if config.stamp_series_id and series_id is not None:
+ for row in rows:
+ row["series_id"] = series_id
+ return rows
+
+
+def _walk(
+ session: requests.Session,
+ api_key: str,
+ config: FredEndpointConfig,
+ extra_params: dict[str, Any],
+ start_offset: int,
+ series_id: Optional[str],
+ on_page_complete: Callable[[int], None],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield one batch per response, walking offset pages until FRED returns a short page.
+
+ `on_page_complete(next_offset)` runs after a full page has been yielded so the caller can
+ checkpoint. Re-yielding the last page after a crash is harmless: the merge de-duplicates
+ on the endpoint's primary key.
+ """
+ params = {**config.params, **extra_params}
+
+ if not config.paginated:
+ rows = _extract_rows(_fetch(session, api_key, config.path, params), config, series_id)
+ if rows:
+ yield rows
+ return
+
+ offset = start_offset
+ while True:
+ payload = _fetch(session, api_key, config.path, {**params, "limit": config.page_size, "offset": offset})
+ page_size = len(payload.get(config.data_key) or [])
+ rows = _extract_rows(payload, config, series_id)
+ if rows:
+ yield rows
+
+ # FRED reports `count`/`offset`/`limit` alongside the rows, but a short page is the
+ # one termination signal that holds for every endpoint.
+ if page_size < config.page_size:
+ break
+
+ offset += config.page_size
+ on_page_complete(offset)
+
+
+def _checkpoint(
+ resumable_source_manager: ResumableSourceManager[FredResumeConfig], series_index: int
+) -> Callable[[int], None]:
+ def save(next_offset: int) -> None:
+ resumable_source_manager.save_state(FredResumeConfig(series_index=series_index, offset=next_offset))
+
+ return save
+
+
+def get_rows(
+ api_key: str,
+ series_ids: list[str],
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FredResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = FRED_ENDPOINTS[endpoint]
+ session = make_tracked_session(redact_values=(api_key,))
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ logger.debug(
+ f"FRED: resuming {endpoint} from series_index={resume_config.series_index}, offset={resume_config.offset}"
+ )
+
+ if not config.per_series:
+ yield from _walk(
+ session,
+ api_key,
+ config,
+ {},
+ resume_config.offset if resume_config is not None else 0,
+ None,
+ _checkpoint(resumable_source_manager, 0),
+ )
+ return
+
+ resume_index = resume_config.series_index if resume_config is not None else 0
+ for index, series_id in enumerate(series_ids):
+ if index < resume_index:
+ continue
+
+ start_offset = resume_config.offset if (resume_config is not None and index == resume_index) else 0
+
+ yield from _walk(
+ session,
+ api_key,
+ config,
+ {"series_id": series_id},
+ start_offset,
+ series_id,
+ _checkpoint(resumable_source_manager, index),
+ )
+
+ # Checkpoint the next series so a resume doesn't rewalk the one just finished.
+ resumable_source_manager.save_state(FredResumeConfig(series_index=index + 1, offset=0))
+
+
+def validate_credentials(api_key: str, series_id: str) -> tuple[bool, str | None]:
+ """Probe `/fred/series` once: it checks the key and the first series id together."""
+ session = make_tracked_session(redact_values=(api_key,))
+ try:
+ _fetch(session, api_key, "/series", {"series_id": series_id})
+ except FredAuthenticationError:
+ return False, "Invalid FRED API key. Check the key you requested at fred.stlouisfed.org."
+ except FredRequestError:
+ return False, f"FRED has no series with the ID {series_id}. Check it on fred.stlouisfed.org."
+ except Exception:
+ return False, "Could not reach the FRED API. Try again in a moment."
+ return True, None
+
+
+def fred_source(
+ api_key: str,
+ series_ids: list[str],
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FredResumeConfig],
+) -> SourceResponse:
+ config = FRED_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ series_ids=series_ids,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=list(config.primary_keys),
+ # Per-series endpoints emit one series at a time, so the stream restarts at each
+ # series' earliest row and is not globally ordered by any column.
+ sort_mode=None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fred/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/settings.py
new file mode 100644
index 000000000000..9736c65ed650
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/settings.py
@@ -0,0 +1,126 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# FRED's earliest addressable real-time date. `/fred/releases/dates` otherwise defaults
+# `realtime_start` to the first day of the current year, which would clip the calendar to
+# whatever year the sync happens to run in.
+FRED_EARLIEST_REALTIME_DATE = "1776-07-04"
+
+
+@dataclass
+class FredEndpointConfig:
+ name: str
+ path: str
+ # FRED nests every collection under a key named after the resource; `seriess` is the
+ # API's own (sic) spelling for the series list.
+ data_key: str
+ primary_keys: list[str]
+ # Endpoints taking a `series_id`: fetched once per series in the source's series list.
+ per_series: bool = False
+ # Stamp the requested series id onto each row. Observations and the per-series lookups
+ # return no series identifier of their own, so without it their rows can't be told
+ # apart once several series land in the same table.
+ stamp_series_id: bool = False
+ # Only the collection endpoints accept limit/offset. The per-series lookups return
+ # their whole (small) result in a single response.
+ paginated: bool = False
+ page_size: int = 1000
+ # Static query params: ordering (stable page boundaries) and realtime window.
+ params: dict[str, str] = field(default_factory=dict)
+
+
+FRED_ENDPOINTS: dict[str, FredEndpointConfig] = {
+ "series": FredEndpointConfig(
+ name="series",
+ path="/series",
+ data_key="seriess",
+ primary_keys=["id"],
+ per_series=True,
+ ),
+ "observations": FredEndpointConfig(
+ name="observations",
+ path="/series/observations",
+ data_key="observations",
+ primary_keys=["series_id", "date"],
+ per_series=True,
+ stamp_series_id=True,
+ paginated=True,
+ # The observations endpoint allows (and defaults to) 100000 rows per response, so
+ # all but the longest daily series come back in one request.
+ page_size=100000,
+ params={"sort_order": "asc"},
+ ),
+ "series_categories": FredEndpointConfig(
+ name="series_categories",
+ path="/series/categories",
+ data_key="categories",
+ primary_keys=["series_id", "id"],
+ per_series=True,
+ stamp_series_id=True,
+ ),
+ "series_tags": FredEndpointConfig(
+ name="series_tags",
+ path="/series/tags",
+ data_key="tags",
+ primary_keys=["series_id", "name"],
+ per_series=True,
+ stamp_series_id=True,
+ params={"order_by": "name", "sort_order": "asc"},
+ ),
+ "series_releases": FredEndpointConfig(
+ name="series_releases",
+ path="/series/release",
+ data_key="releases",
+ primary_keys=["series_id", "id"],
+ per_series=True,
+ stamp_series_id=True,
+ ),
+ "releases": FredEndpointConfig(
+ name="releases",
+ path="/releases",
+ data_key="releases",
+ primary_keys=["id"],
+ paginated=True,
+ params={"order_by": "release_id", "sort_order": "asc"},
+ ),
+ "release_dates": FredEndpointConfig(
+ name="release_dates",
+ path="/releases/dates",
+ data_key="release_dates",
+ primary_keys=["release_id", "date"],
+ paginated=True,
+ params={
+ "order_by": "release_id",
+ "sort_order": "asc",
+ "include_release_dates_with_no_data": "true",
+ "realtime_start": FRED_EARLIEST_REALTIME_DATE,
+ },
+ ),
+ "sources": FredEndpointConfig(
+ name="sources",
+ path="/sources",
+ data_key="sources",
+ primary_keys=["id"],
+ paginated=True,
+ params={"order_by": "source_id", "sort_order": "asc"},
+ ),
+ "tags": FredEndpointConfig(
+ name="tags",
+ path="/tags",
+ data_key="tags",
+ primary_keys=["name"],
+ paginated=True,
+ params={"order_by": "name", "sort_order": "asc"},
+ ),
+}
+
+ENDPOINTS = tuple(FRED_ENDPOINTS.keys())
+
+# Every table is full refresh. `/fred/series/observations` does take a server-side
+# `observation_start` filter, but the pipeline hands a source one watermark shared by every
+# configured series, and FRED restates published observations after the fact. Driving
+# `observation_start` off that single watermark would skip the whole back history of a
+# series added after the first sync, and miss revisions to points behind it. Full pulls are
+# cheap here (one request covers up to 100000 observations), so correctness wins.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fred/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/source.py
index d16c1eee4e6c..fbdf8b52b823 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fred/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/source.py
@@ -1,30 +1,137 @@
-from typing import cast
+from typing import Optional, cast
from 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.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.fred import (
+ SERIES_ID_PATTERN,
+ FredResumeConfig,
+ fred_source,
+ parse_series_ids,
+ validate_credentials as validate_fred_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fred import FredSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FredSource(SimpleSource[FredSourceConfig]):
+class FredSource(ResumableSource[FredSourceConfig, FredResumeConfig]):
+ api_docs_url = "https://fred.stlouisfed.org/docs/api/fred/"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FRED
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "FRED authentication failed": "Your FRED API key is invalid or is not registered. Request a key at fred.stlouisfed.org and reconnect.",
+ "FRED rejected the request": "FRED rejected the request. Check that every series ID in your source settings exists on fred.stlouisfed.org.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.FRED,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
- label="FRED (Federal Reserve Economic Data), Federal Reserve Bank of St. Louis",
+ label="FRED",
+ keywords=["federal reserve", "economic data", "st louis fed", "macro"],
+ caption="""Pull US and international economic time series from FRED, the Federal Reserve Bank of St. Louis database, into the PostHog Data warehouse.
+
+Request a free API key at [fred.stlouisfed.org/docs/api/api_key.html](https://fred.stlouisfed.org/docs/api/api_key.html). FRED has around 800,000 series, so pick the ones you want: a series ID is the code at the end of its FRED page URL, such as `UNRATE` for the unemployment rate or `CPIAUCSL` for CPI.""",
iconPath="/static/services/fred.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/fred",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="series_ids",
+ label="Series IDs",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="UNRATE, CPIAUCSL, GDPC1, DGS10",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.fred.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: FredSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: FredSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ series_ids = parse_series_ids(config.series_ids)
+ if not series_ids:
+ return False, "Enter at least one FRED series ID"
+
+ invalid = next((series_id for series_id in series_ids if not SERIES_ID_PATTERN.match(series_id)), None)
+ if invalid is not None:
+ return False, f"{invalid} is not a valid FRED series ID. IDs look like UNRATE or CPIAUCSL."
+
+ return validate_fred_credentials(config.api_key, series_ids[0])
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FredResumeConfig]:
+ return ResumableSourceManager[FredResumeConfig](inputs, FredResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FredSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FredResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return fred_source(
+ api_key=config.api_key,
+ series_ids=parse_series_ids(config.series_ids),
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fred/tests/test_fred.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/tests/test_fred.py
new file mode 100644
index 000000000000..cfcf2e08d266
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/tests/test_fred.py
@@ -0,0 +1,337 @@
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.fred import (
+ FRED_BASE_URL,
+ FredApiError,
+ FredAuthenticationError,
+ FredRequestError,
+ FredResumeConfig,
+ _build_url,
+ fred_source,
+ get_rows,
+ parse_series_ids,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.settings import (
+ FRED_ENDPOINTS,
+ FredEndpointConfig,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.fred.fred"
+
+
+def _make_manager(resume_state: FredResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(body: Any = None, status_code: int = 200) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = {} if body is None else body
+ return response
+
+
+def _query(call: Any) -> dict[str, list[str]]:
+ return parse_qs(urlparse(call.args[0]).query)
+
+
+class TestFredTransport:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("UNRATE", ["UNRATE"]),
+ ("UNRATE,CPIAUCSL", ["UNRATE", "CPIAUCSL"]),
+ ("UNRATE, CPIAUCSL ; GDPC1", ["UNRATE", "CPIAUCSL", "GDPC1"]),
+ ("UNRATE\nCPIAUCSL\n\nGDPC1\n", ["UNRATE", "CPIAUCSL", "GDPC1"]),
+ ("UNRATE, UNRATE, CPIAUCSL", ["UNRATE", "CPIAUCSL"]),
+ (" ", []),
+ ("", []),
+ ],
+ )
+ def test_parse_series_ids(self, raw, expected):
+ # A field pasted as "UNRATE, CPIAUCSL" must not be sent to FRED as one series id.
+ assert parse_series_ids(raw) == expected
+
+ def test_build_url_drops_none_params(self):
+ url = _build_url("/series", {"series_id": "UNRATE", "offset": None})
+ assert url == f"{FRED_BASE_URL}/series?series_id=UNRATE"
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_every_request_asks_for_json(self, mock_session):
+ # FRED defaults to XML; without file_type=json the response body isn't parseable.
+ mock_session.return_value.get.return_value = _response({"seriess": [{"id": "UNRATE"}]})
+
+ list(get_rows("key", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert _query(mock_session.return_value.get.call_args)["file_type"] == ["json"]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_api_key_is_registered_for_redaction(self, mock_session):
+ # The key rides in the query string, so the tracked transport has to mask it in
+ # logged URLs and captured samples.
+ mock_session.return_value.get.return_value = _response({"seriess": []})
+
+ list(get_rows("secret-key", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert mock_session.call_args.kwargs["redact_values"] == ("secret-key",)
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_unpaginated_endpoint_issues_one_request_without_paging_params(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"seriess": [{"id": "UNRATE"}]})
+
+ batches = list(get_rows("key", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert batches == [[{"id": "UNRATE"}]]
+ assert mock_session.return_value.get.call_count == 1
+ query = _query(mock_session.return_value.get.call_args)
+ assert "limit" not in query
+ assert "offset" not in query
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_paginated_endpoint_walks_offsets_until_short_page(self, mock_session):
+ small_page = FredEndpointConfig(
+ name="releases", path="/releases", data_key="releases", primary_keys=["id"], paginated=True, page_size=2
+ )
+ mock_session.return_value.get.side_effect = [
+ _response({"releases": [{"id": 1}, {"id": 2}]}),
+ _response({"releases": [{"id": 3}]}),
+ ]
+
+ with mock.patch.dict(FRED_ENDPOINTS, {"releases": small_page}):
+ batches = list(get_rows("key", [], "releases", mock.MagicMock(), _make_manager()))
+
+ assert batches == [[{"id": 1}, {"id": 2}], [{"id": 3}]]
+ offsets = [_query(call).get("offset") for call in mock_session.return_value.get.call_args_list]
+ assert offsets == [["0"], ["2"]]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_paginated_endpoint_stops_on_empty_first_page(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"releases": []})
+
+ batches = list(get_rows("key", [], "releases", mock.MagicMock(), _make_manager()))
+
+ assert batches == []
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_per_series_endpoint_stamps_series_id_on_every_row(self, mock_session):
+ # Observations carry only date/value, so without the stamp two series collide on the
+ # ["series_id", "date"] primary key and merge into each other.
+ mock_session.return_value.get.side_effect = [
+ _response({"observations": [{"date": "2024-01-01", "value": "3.7"}]}),
+ _response({"observations": [{"date": "2024-01-01", "value": "308.4"}]}),
+ ]
+
+ batches = list(get_rows("key", ["UNRATE", "CPIAUCSL"], "observations", mock.MagicMock(), _make_manager()))
+
+ assert batches == [
+ [{"date": "2024-01-01", "value": "3.7", "series_id": "UNRATE"}],
+ [{"date": "2024-01-01", "value": "308.4", "series_id": "CPIAUCSL"}],
+ ]
+ requested = [_query(call)["series_id"] for call in mock_session.return_value.get.call_args_list]
+ assert requested == [["UNRATE"], ["CPIAUCSL"]]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_series_rows_are_not_stamped(self, mock_session):
+ # `series` rows already carry the id, so a stamp would add a duplicate column.
+ mock_session.return_value.get.return_value = _response({"seriess": [{"id": "UNRATE", "title": "Unemployment"}]})
+
+ batches = list(get_rows("key", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert batches == [[{"id": "UNRATE", "title": "Unemployment"}]]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resume_skips_completed_series_and_restarts_mid_offset(self, mock_session):
+ small_page = FredEndpointConfig(
+ name="observations",
+ path="/series/observations",
+ data_key="observations",
+ primary_keys=["series_id", "date"],
+ per_series=True,
+ stamp_series_id=True,
+ paginated=True,
+ page_size=2,
+ )
+ mock_session.return_value.get.side_effect = [
+ _response({"observations": [{"date": "2024-03-01"}]}),
+ _response({"observations": [{"date": "2024-01-01"}]}),
+ ]
+ manager = _make_manager(FredResumeConfig(series_index=1, offset=4))
+
+ with mock.patch.dict(FRED_ENDPOINTS, {"observations": small_page}):
+ list(get_rows("key", ["UNRATE", "CPIAUCSL", "GDPC1"], "observations", mock.MagicMock(), manager))
+
+ calls = mock_session.return_value.get.call_args_list
+ assert [_query(call)["series_id"][0] for call in calls] == ["CPIAUCSL", "GDPC1"]
+ # The saved offset applies only to the series it was saved against.
+ assert [_query(call)["offset"][0] for call in calls] == ["4", "0"]
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_state_is_saved_after_each_page_and_each_series(self, mock_session):
+ small_page = FredEndpointConfig(
+ name="observations",
+ path="/series/observations",
+ data_key="observations",
+ primary_keys=["series_id", "date"],
+ per_series=True,
+ stamp_series_id=True,
+ paginated=True,
+ page_size=2,
+ )
+ mock_session.return_value.get.side_effect = [
+ _response({"observations": [{"date": "2024-01-01"}, {"date": "2024-01-02"}]}),
+ _response({"observations": [{"date": "2024-01-03"}]}),
+ _response({"observations": [{"date": "2024-01-01"}]}),
+ ]
+ manager = _make_manager()
+
+ with mock.patch.dict(FRED_ENDPOINTS, {"observations": small_page}):
+ list(get_rows("key", ["UNRATE", "CPIAUCSL"], "observations", mock.MagicMock(), manager))
+
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ FredResumeConfig(series_index=0, offset=2),
+ FredResumeConfig(series_index=1, offset=0),
+ FredResumeConfig(series_index=2, offset=0),
+ ]
+
+ @pytest.mark.parametrize(
+ "status_code, error_message, expected_exception",
+ [
+ (400, "Bad Request. The value for variable api_key is not registered.", FredAuthenticationError),
+ (400, "Bad Request. The series does not exist.", FredRequestError),
+ (401, "", FredAuthenticationError),
+ (403, "", FredAuthenticationError),
+ (429, "Too Many Requests.", FredApiError),
+ (500, "", FredApiError),
+ ],
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_error_status_mapping(self, mock_session, status_code, error_message, expected_exception):
+ mock_session.return_value.get.return_value = _response(
+ {"error_code": status_code, "error_message": error_message}, status_code=status_code
+ )
+
+ with pytest.raises(expected_exception):
+ list(get_rows("key", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ @pytest.mark.parametrize("status_code", [400, 401, 429, 500])
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_errors_never_leak_the_api_key(self, mock_session, status_code):
+ # The key travels as a query param, so an exception built from the request URL would
+ # write it into logs and into the failure surfaced to the user.
+ mock_session.return_value.get.return_value = _response(
+ {"error_message": "Bad Request. The value for variable api_key is not registered."},
+ status_code=status_code,
+ )
+
+ with pytest.raises(FredApiError) as error:
+ list(get_rows("super-secret", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert "super-secret" not in str(error.value)
+
+ @pytest.mark.parametrize(
+ "raised",
+ [
+ requests.ConnectionError(
+ "HTTPSConnectionPool(host='api.stlouisfed.org', port=443): Max retries exceeded with "
+ "url: /fred/series?series_id=UNRATE&api_key=super-secret&file_type=json"
+ ),
+ requests.ReadTimeout(
+ "HTTPSConnectionPool(host='api.stlouisfed.org', port=443): Read timed out. "
+ "url: /fred/series?api_key=super-secret"
+ ),
+ ],
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_transport_errors_never_leak_the_api_key(self, mock_session, raised):
+ # requests' own connection/timeout exceptions embed the prepared URL, api_key and all,
+ # and the pipeline persists that text as `latest_error`.
+ mock_session.return_value.get.side_effect = raised
+
+ with pytest.raises(FredApiError) as error:
+ list(get_rows("super-secret", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert "super-secret" not in str(error.value)
+ # `from None` so the suppressed original can't be re-rendered into the chained message.
+ assert error.value.__cause__ is None
+ assert error.value.__suppress_context__
+ assert type(raised).__name__ in str(error.value)
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_transport_errors_stay_retryable(self, mock_session):
+ # A dropped connection is not a bad key or a bad series id, so it must not match one of
+ # the source's non-retryable error prefixes.
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+
+ with pytest.raises(FredApiError) as error:
+ list(get_rows("key", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert not isinstance(error.value, FredAuthenticationError | FredRequestError)
+ assert not str(error.value).startswith(("FRED authentication failed", "FRED rejected the request"))
+
+ @pytest.mark.parametrize(
+ "body, expected_type",
+ [
+ # FRED serves HTML from its edge on some failures, so the body may not be JSON at all.
+ (ValueError("not json"), FredApiError),
+ # ...and a JSON body that isn't an object has no `error_message` to read.
+ (["unexpected"], FredApiError),
+ ],
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_unparseable_error_bodies_still_raise(self, mock_session, body, expected_type):
+ response = _response(status_code=500)
+ if isinstance(body, Exception):
+ response.json.side_effect = body
+ else:
+ response.json.return_value = body
+ mock_session.return_value.get.return_value = response
+
+ with pytest.raises(expected_type) as error:
+ list(get_rows("key", ["UNRATE"], "series", mock.MagicMock(), _make_manager()))
+
+ assert "status=500" in str(error.value)
+
+ @pytest.mark.parametrize(
+ "status_code, error_message, expected",
+ [
+ (200, "", (True, None)),
+ (
+ 400,
+ "Bad Request. The value for variable api_key is not registered.",
+ (False, "Invalid FRED API key. Check the key you requested at fred.stlouisfed.org."),
+ ),
+ (
+ 400,
+ "Bad Request. The series does not exist.",
+ (False, "FRED has no series with the ID NOPE. Check it on fred.stlouisfed.org."),
+ ),
+ (500, "", (False, "Could not reach the FRED API. Try again in a moment.")),
+ ],
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, error_message, expected):
+ mock_session.return_value.get.return_value = _response(
+ {"seriess": [], "error_message": error_message}, status_code=status_code
+ )
+
+ assert validate_credentials("key", "NOPE") == expected
+
+ @pytest.mark.parametrize("endpoint", list(FRED_ENDPOINTS))
+ def test_fred_source_response_shape(self, endpoint):
+ response = fred_source("key", ["UNRATE"], endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == FRED_ENDPOINTS[endpoint].primary_keys
+ # Rows restart at each series' earliest date, so no global ordering may be claimed.
+ assert response.sort_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fred/tests/test_fred_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/tests/test_fred_source.py
new file mode 100644
index 000000000000..39b2d76cff96
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fred/tests/test_fred_source.py
@@ -0,0 +1,167 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.fred import FredResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.settings import ENDPOINTS, FRED_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.fred.source import FredSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fred import FredSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.fred.source"
+
+
+class TestFredSource:
+ def setup_method(self):
+ self.source = FredSource()
+ self.team_id = 123
+ self.config = FredSourceConfig(api_key="key", series_ids="UNRATE, CPIAUCSL")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.FRED
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Fred"
+ assert config.label == "FRED"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/fred.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key", "series_ids"]
+
+ @pytest.mark.parametrize(
+ "field_name, field_type, secret",
+ [
+ ("api_key", SourceFieldInputConfigType.PASSWORD, True),
+ ("series_ids", SourceFieldInputConfigType.TEXTAREA, False),
+ ],
+ )
+ def test_field_types(self, field_name, field_type, secret):
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)
+
+ assert field.type == field_type
+ assert field.secret is secret
+ assert field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "FRED authentication failed: Bad Request. The value for variable api_key is not registered.",
+ "FRED rejected the request (path=/series): Bad Request. The series does not exist.",
+ ],
+ )
+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "FRED API error: status=429, path=/series/observations, message=Too Many Requests.",
+ "FRED API error: status=503, path=/releases, message=",
+ ],
+ )
+ def test_non_retryable_errors_leave_transient_failures_retryable(self, other_error):
+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # The pipeline hands a source one watermark for the whole table, but observations are
+ # fetched per series and FRED restates published values, so nothing may claim
+ # incremental sync off `observation_start`.
+ assert not any(schema.supports_incremental for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_get_schemas_filters_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["series", "observations"])
+ assert {schema.name for schema in schemas} == {"series", "observations"}
+
+ @pytest.mark.parametrize(
+ "endpoint, config",
+ list(FRED_ENDPOINTS.items()),
+ )
+ def test_series_scoped_tables_key_on_series_id(self, endpoint, config):
+ # Rows from every configured series land in one table, so a key without `series_id`
+ # is not unique table-wide and every later merge multi-matches it.
+ if config.stamp_series_id:
+ assert "series_id" in config.primary_keys
+ else:
+ assert "series_id" not in config.primary_keys
+
+ @pytest.mark.parametrize(
+ "series_ids, expected_error",
+ [
+ ("", "Enter at least one FRED series ID"),
+ (" ", "Enter at least one FRED series ID"),
+ ("UNRATE, GDP*", "GDP* is not a valid FRED series ID. IDs look like UNRATE or CPIAUCSL."),
+ (
+ "https://fred.stlouisfed.org/series/UNRATE",
+ "https://fred.stlouisfed.org/series/UNRATE is not a valid FRED series ID. IDs look like UNRATE or CPIAUCSL.",
+ ),
+ ],
+ )
+ def test_validate_credentials_rejects_bad_series_ids_without_calling_fred(self, series_ids, expected_error):
+ config = FredSourceConfig(api_key="key", series_ids=series_ids)
+
+ with mock.patch(f"{SOURCE_MODULE}.validate_fred_credentials") as mock_validate:
+ valid, error = self.source.validate_credentials(config, self.team_id)
+
+ assert valid is False
+ assert error == expected_error
+ mock_validate.assert_not_called()
+
+ @pytest.mark.parametrize("is_valid", [True, False])
+ @mock.patch(f"{SOURCE_MODULE}.validate_fred_credentials")
+ def test_validate_credentials_probes_the_first_series(self, mock_validate, is_valid):
+ mock_validate.return_value = (is_valid, None if is_valid else "Invalid FRED API key.")
+
+ valid, error = self.source.validate_credentials(self.config, self.team_id)
+
+ assert valid is is_valid
+ assert (error is None) is is_valid
+ mock_validate.assert_called_once_with("key", "UNRATE")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FredResumeConfig
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_source_for_pipeline_plumbs_schema_name(self, endpoint):
+ inputs = mock.MagicMock()
+ inputs.schema_name = endpoint
+
+ response = self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert response.name == endpoint
+ assert response.primary_keys == FRED_ENDPOINTS[endpoint].primary_keys
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.fred.source.fred_source")
+ def test_source_for_pipeline_splits_the_series_id_field(self, mock_fred_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "observations"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_fred_source.call_args.kwargs["series_ids"] == ["UNRATE", "CPIAUCSL"]
+
+ def test_documented_tables_render_without_credentials(self):
+ assert self.source.lists_tables_without_credentials is True
+ assert {table["name"] for table in self.source.get_documented_tables()} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ # Descriptions are keyed by schema name, so a renamed endpoint silently drops back to
+ # LLM-derived descriptions.
+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)
+ assert self.source.get_canonical_descriptions() == CANONICAL_DESCRIPTIONS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fred.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fred.py
index b2e3497f12f5..5775ca81cfb5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fred.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fred.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class FredSourceConfig(config.Config):
- pass
+ api_key: str
+ series_ids: str