: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 finnworlds import source (#66759)
Tom Owersdda782ac7629
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 16948091588f..b6ad01691d8f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -111,6 +111,7 @@ the row lists both.| eventbrite | HTTP | requests | ✅ || everhour | HTTP | requests | ✅ || fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |+| finnworlds | HTTP | requests | ✅ || front | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |@@ -394,7 +395,6 @@ doesn't conflict with concurrent PRs.- finage- financial_modelling- finnhub-- finnworlds- firebase- firebolt- firehydrantdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/canonical_descriptions.pynew file mode 100644index 000000000000..b33b9304d31d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/canonical_descriptions.py@@ -0,0 +1,174 @@+"""Canonical, documentation-sourced descriptions for Finnworlds endpoints and columns.++Sourced from the official Finnworlds API documentation (https://finnworlds.com/documentation/).+Keyed by the endpoint names in `settings.py` `FINNWORLDS_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Finnworlds table. Columns absent here fall back to LLM+enrichment. The connector injects `ticker` (and `period` for fundamentals) onto every row, so those+appear as columns even though they originate from the request, not the record body.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++DOCS_URL = "https://finnworlds.com/documentation/"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "company_information": {+ "description": "Company profile and reference data (sector, industry, identifiers, executives).",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the data was requested for.",+ "name": "Company legal/display name.",+ "cik": "SEC Central Index Key for the company.",+ "isin": "International Securities Identification Number.",+ "cusip": "CUSIP identifier.",+ "lei": "Legal Entity Identifier.",+ "sector": "Industry sector the company belongs to.",+ "industry": "Industry classification of the company.",+ "sic_code": "Standard Industrial Classification code.",+ "sic_name": "Standard Industrial Classification label.",+ "website": "Company website URL.",+ "about": "Free-text description of the company.",+ },+ },+ "income_statements": {+ "description": "Income statement line items per reporting period for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the statement belongs to.",+ "period": "Reporting period grain (annual or quarterly).",+ "date": "Fiscal period end date.",+ "total_revenue": "Total revenue for the period.",+ "cost_of_revenue": "Cost of revenue for the period.",+ "gross_profit": "Gross profit (revenue minus cost of revenue).",+ "operating_income": "Operating income for the period.",+ "pretax_income": "Income before income taxes.",+ "tax_provision": "Income tax expense for the period.",+ "net_income": "Net income for the period.",+ "basic_eps": "Basic earnings per share.",+ "diluted_eps": "Diluted earnings per share.",+ "ebit": "Earnings before interest and taxes.",+ "ebitda": "Earnings before interest, taxes, depreciation, and amortization.",+ },+ },+ "balance_sheets": {+ "description": "Balance sheet line items per reporting period for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the statement belongs to.",+ "period": "Reporting period grain (annual or quarterly).",+ "date": "Fiscal period end date.",+ "total_assets": "Total assets at period end.",+ "total_liabilities_net_minority_interest": "Total liabilities net of minority interest.",+ "stockholders_equity": "Total stockholders' equity.",+ "net_debt": "Net debt (total debt minus cash and equivalents).",+ "working_capital": "Working capital at period end.",+ "ordinary_shares_number": "Number of ordinary shares outstanding.",+ "share_issued": "Number of shares issued.",+ },+ },+ "cash_flows": {+ "description": "Cash flow statement line items per reporting period for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the statement belongs to.",+ "period": "Reporting period grain (annual or quarterly).",+ "date": "Fiscal period end date.",+ "operating_cash_flow": "Net cash from operating activities.",+ "investing_cash_flow": "Net cash from investing activities.",+ "financing_cash_flow": "Net cash from financing activities.",+ "free_cash_flow": "Free cash flow for the period.",+ "capital_expenditure": "Capital expenditure for the period.",+ },+ },+ "financial_ratios": {+ "description": "Current snapshot of valuation and health ratios for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the ratios belong to.",+ "date": "Date the ratios were computed (as of).",+ "pe_ratio": "Price-to-earnings ratio.",+ "eps": "Earnings per share.",+ "market_capitalization": "Market capitalization.",+ "debt_equity_ratio": "Debt-to-equity ratio.",+ "altman_z_score": "Altman Z-score bankruptcy risk metric.",+ },+ },+ "dividends": {+ "description": "Historical dividend payments for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the dividend belongs to.",+ "date": "Official record date of the dividend payment.",+ "dividend_rate": "Dividend amount paid per share.",+ },+ },+ "stock_splits": {+ "description": "Historical stock split events for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the split belongs to.",+ "date": "Date the split took effect.",+ "stock_split": "Split ratio (e.g. 4:1).",+ },+ },+ "stock_prices": {+ "description": "Daily OHLC price candles and volume for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the candle belongs to.",+ "date": "Trading date of the candle.",+ "open": "Opening price.",+ "high": "Intraday high price.",+ "low": "Intraday low price.",+ "close": "Closing price.",+ "adjusted_close": "Closing price adjusted for splits and dividends.",+ "trade_volume": "Number of shares traded.",+ "stock_split": "Split ratio applied on this date, if any.",+ "dividend_rate": "Dividend paid on this date, if any.",+ },+ },+ "company_ratings": {+ "description": "Analyst ratings and price targets for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the rating belongs to.",+ "analyst_name": "Name of the analyst issuing the rating.",+ "analyst_firm": "Firm the analyst represents.",+ "analyst_role": "Role of the analyst at the firm.",+ "date_rating": "Date the rating was issued.",+ "target_date": "Date the price target applies to.",+ "price_target": "Analyst's price target.",+ "rated": "Rating direction (e.g. upgrade, downgrade, maintain).",+ "conclusion": "Analyst's conclusion or recommendation.",+ },+ },+ "sec_filings": {+ "description": "SEC filings (Form type, title, EDGAR link) for a company.",+ "docs_url": DOCS_URL,+ "columns": {+ "ticker": "Stock ticker symbol the filing belongs to.",+ "date": "Filing date.",+ "title": "Filing title.",+ "form_type": "SEC form type (e.g. 10-K, 10-Q, 8-K).",+ "file_number": "SEC file number associated with the filing.",+ "url": "EDGAR index URL for the filing.",+ },+ },+ "bond_yields": {+ "description": "Government bond yields by country and maturity. Global, not company-specific.",+ "docs_url": DOCS_URL,+ "columns": {+ "country": "Country the bond is issued by.",+ "region": "Region the country belongs to.",+ "type": "Bond maturity (e.g. 10Y).",+ "yield": "Current yield.",+ "datetime": "Timestamp the yield was recorded.",+ "price_change_day": "Yield change over the day.",+ "percentage_week": "Percentage change over the week.",+ "percentage_month": "Percentage change over the month.",+ "percentage_year": "Percentage change over the year.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/finnworlds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/finnworlds.pynew file mode 100644index 000000000000..994c443b9d11--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/finnworlds.py@@ -0,0 +1,275 @@+import re+from collections.abc import Iterator+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 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.finnworlds.settings import (+ FINNWORLDS_ENDPOINTS,+ FinnworldsEndpointConfig,+ ResponseMode,+)++FINNWORLDS_BASE_URL = "https://api.finnworlds.com/api/v1"++# Finnworlds returns HTTP 200 even for an invalid key, signalling the failure only in the JSON body+# (e.g. {"error": "Invalid key"}). These substrings (lower-cased) mark a body-level error that retrying+# can never fix, so the sync fails fast via FinnworldsAuthError instead of treating the ticker as empty.+_AUTH_ERROR_MARKERS = ("invalid key", "forbidden", "unauthorized", "expired", "not authorized")++REQUEST_TIMEOUT_SECONDS = 60++# Every ticker costs one request per enabled ticker-backed table on each sync, so cap the list to bound+# the outbound fan-out (and the credit burn) a single config can trigger. 500 comfortably covers a large+# watchlist like the S&P 500 while rejecting paste-the-whole-exchange configs.+MAX_TICKERS = 500+++class FinnworldsRetryableError(Exception):+ """A transient API error (429 / 5xx) worth retrying."""+++class FinnworldsAuthError(Exception):+ """A permanent authentication/authorization failure — surfaced via get_non_retryable_errors."""+++def parse_tickers(raw: str | None) -> list[str]:+ """Split the user's free-text ticker list into a clean, de-duplicated, upper-cased list.++ Accepts commas, whitespace, and newlines as separators so users can paste a watchlist in any+ common shape. Order is preserved (first occurrence wins) for stable, predictable sync output.++ Raises ``ValueError`` when more than ``MAX_TICKERS`` distinct symbols are supplied so an oversized+ config is rejected before the pipeline starts scheduling a request per ticker per table.+ """+ if not raw:+ return []+ tokens = raw.replace(",", " ").split()+ seen: set[str] = set()+ tickers: list[str] = []+ for token in tokens:+ symbol = token.strip().upper()+ if symbol and symbol not in seen:+ seen.add(symbol)+ tickers.append(symbol)+ if len(tickers) > MAX_TICKERS:+ raise ValueError(f"Too many tickers: at most {MAX_TICKERS} are allowed per source.")+ return tickers+++def _build_url(path: str, params: dict[str, str]) -> str:+ return f"{FINNWORLDS_BASE_URL}/{path}?{urlencode(params)}"+++# The API key rides in the `key` query param, so it ends up in `response.url`. `raise_for_status()`+# embeds that URL in its message, which would otherwise leak the key into the sync's stored error and logs.+_KEY_RE = re.compile(r"(key=)[^&\s]+", re.IGNORECASE)+++def _redact_key(text: str) -> str:+ return _KEY_RE.sub(r"\1REDACTED", text)+++@retry(+ retry=retry_if_exception_type((FinnworldsRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise FinnworldsRetryableError(f"Finnworlds API error (retryable): status={response.status_code}")++ try:+ response.raise_for_status()+ except requests.HTTPError as exc:+ # Re-raise with the `key` redacted so the credential never reaches stored errors / logs, keeping the+ # `... for url: https://api.finnworlds.com` prefix intact for `get_non_retryable_errors()`.+ raise requests.HTTPError(_redact_key(str(exc)), response=exc.response) from None++ payload = response.json()+ if not isinstance(payload, dict):+ return {}+ return payload+++def _payload_error(payload: dict[str, Any]) -> str | None:+ """Return the body-level error message, if any. Finnworlds reports failures in the body at 200."""+ error = payload.get("error")+ if isinstance(error, str) and error.strip():+ return error+ status = payload.get("status")+ if isinstance(status, dict):+ code = status.get("code")+ if code is not None and str(code) != "200":+ message = status.get("message") or status.get("details") or f"status {code}"+ return str(message)+ return None+++def _raise_if_auth_error(error_message: str) -> None:+ lowered = error_message.lower()+ if any(marker in lowered for marker in _AUTH_ERROR_MARKERS):+ raise FinnworldsAuthError(f"Finnworlds authentication failed: {error_message}")+++def _extract_rows(payload: dict[str, Any], config: FinnworldsEndpointConfig) -> list[dict[str, Any]]:+ result = payload.get("result", {})+ result = result if isinstance(result, dict) else {}++ rows: Any+ if config.response_mode == ResponseMode.OUTPUT_ARRAY:+ output = result.get("output", {})+ rows = output.get(config.data_key, []) if isinstance(output, dict) and config.data_key else []+ elif config.response_mode == ResponseMode.OUTPUT_OBJECT:+ output = result.get("output", {})+ rows = [output] if isinstance(output, dict) and output else []+ elif config.response_mode == ResponseMode.OUTPUT_BARE:+ output = result.get("output", [])+ rows = output if isinstance(output, list) else []+ elif config.response_mode == ResponseMode.RESULT_KEY:+ rows = result.get(config.data_key, []) if config.data_key else []+ else: # TOP_LEVEL+ rows = payload.get(config.data_key, []) if config.data_key else []++ if not isinstance(rows, list):+ return []+ return [row for row in rows if isinstance(row, dict)]+++def _normalize_row(+ row: dict[str, Any], config: FinnworldsEndpointConfig, ticker: str | None, period: str | None+) -> dict[str, Any]:+ """Flatten configured nested objects and inject the identifiers the primary key relies on."""+ for nested_key in config.flatten_keys:+ nested = row.pop(nested_key, None)+ if isinstance(nested, dict):+ # Injected ticker/period below take precedence, so merge the nested object first.+ row = {**nested, **row}+ if config.requires_ticker and ticker is not None:+ row["ticker"] = ticker+ if config.include_period:+ row["period"] = period or "annual"+ return row+++def _fetch_endpoint_rows(+ session: requests.Session,+ config: FinnworldsEndpointConfig,+ api_key: str,+ ticker: str | None,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ params: dict[str, str] = {"key": api_key}+ if ticker is not None:+ params["ticker"] = ticker+ url = _build_url(config.path, params)++ payload = _fetch(session, url, logger)++ error_message = _payload_error(payload)+ if error_message is not None:+ _raise_if_auth_error(error_message)+ # A non-auth error usually means "no data for this identifier" or a tier-gated endpoint; skip+ # the identifier rather than failing the whole sync.+ logger.warning(+ f"Finnworlds {config.name}: skipping ticker={ticker} due to API error: {error_message}",+ )+ return []++ period = None+ if config.include_period:+ result_dict = payload.get("result", {})+ basics = result_dict.get("basics", {}) if isinstance(result_dict, dict) else {}+ period = basics.get("period") if isinstance(basics, dict) else None+ if period is None:+ # The primary key for fundamentals is (ticker, period, date); without a real period every row+ # falls back to "annual", which would silently merge quarterly rows. Surface it when it happens.+ logger.warning(+ f"Finnworlds {config.name}: no period in response for ticker={ticker}; "+ "defaulting to 'annual' (quarterly rows may collide on the primary key)",+ )++ rows = _extract_rows(payload, config)+ return [_normalize_row(row, config, ticker, period) for row in rows]+++def get_rows(+ api_key: str,+ endpoint: str,+ tickers: list[str],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = FINNWORLDS_ENDPOINTS[endpoint]+ # One session reused across every request so urllib3 keeps the connection alive. The API key+ # rides in the query string, so redact it from logged URLs and captured samples.+ session = make_tracked_session(redact_values=(api_key,))++ if not config.requires_ticker:+ rows = _fetch_endpoint_rows(session, config, api_key, None, logger)+ if rows:+ yield rows+ return++ for ticker in tickers:+ rows = _fetch_endpoint_rows(session, config, api_key, ticker, logger)+ if rows:+ # Yield one batch per ticker; the pipeline buffers and re-batches across tickers.+ yield rows+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Probe a cheap ticker-keyed endpoint. The key is valid when the body carries no error.++ Returns (is_valid, error_message). A transient network failure during setup is reported distinctly+ from a bad key so a brief connectivity blip isn't mistaken for an invalid credential — the sync path+ retries the same transient errors via tenacity.+ """+ url = _build_url("information", {"key": api_key, "ticker": "AAPL"})+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(url, timeout=10)+ except (requests.ConnectionError, requests.Timeout) as exc:+ return False, f"Could not reach the Finnworlds API: {type(exc).__name__}. Please try again."+ except Exception:+ # Any other unexpected failure stays fail-closed as a bad key rather than crashing setup.+ return False, "Invalid Finnworlds API key"++ if not response.ok:+ return False, "Invalid Finnworlds API key"+ try:+ payload = response.json()+ except ValueError:+ return False, "Invalid Finnworlds API key"++ if not isinstance(payload, dict):+ return False, "Invalid Finnworlds API key"+ if _payload_error(payload) is not None:+ return False, "Invalid Finnworlds API key"+ return True, None+++def finnworlds_source(+ api_key: str,+ endpoint: str,+ tickers: list[str],+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config = FINNWORLDS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, tickers=tickers, logger=logger),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/settings.pynew file mode 100644index 000000000000..8a3fabf25357--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/settings.py@@ -0,0 +1,143 @@+from dataclasses import dataclass, field+from enum import StrEnum+from typing import Optional+++class ResponseMode(StrEnum):+ """How rows are extracted from a Finnworlds JSON response.++ Finnworlds wraps almost everything in ``{"status": ..., "result": {"basics": {...}, "output": ...}}``,+ but ``output`` is sometimes a named array, sometimes a bare list, and sometimes a single flat object.+ A handful of endpoints break the envelope entirely (e.g. SEC filings keep the array at the top level).+ These shapes are taken from the public docs and have not been curl-verified end to end, so the+ extractor degrades to an empty row set when the documented path is absent.+ """++ # result.output[<data_key>] is a list of records (fundamentals, dividends, splits, OHLC).+ OUTPUT_ARRAY = "output_array"+ # result.output is a single flat object → emitted as one row (financial ratios, company info).+ OUTPUT_OBJECT = "output_object"+ # result.output is itself a bare list of records (bond yields).+ OUTPUT_BARE = "output_bare"+ # result[<data_key>] is a list of records (analyst/company ratings live under result.analysts).+ RESULT_KEY = "result_key"+ # <data_key> is a top-level list, outside the result envelope (SEC filings).+ TOP_LEVEL = "top_level"+++@dataclass+class FinnworldsEndpointConfig:+ name: str # warehouse table name (and ExternalDataSchema.name)+ path: str # API path segment under https://api.finnworlds.com/api/v1/+ response_mode: ResponseMode+ data_key: Optional[str] = None # array/object key for OUTPUT_ARRAY / RESULT_KEY / TOP_LEVEL+ # Most endpoints return data for a single identifier per call, so a full sync fans out over the+ # user's ticker list. Endpoints that return a global list (bond yields) set this False.+ requires_ticker: bool = True+ # Inject result.basics.period into each row so fundamentals from different reporting periods don't+ # collide on the (ticker, period, date) primary key.+ include_period: bool = False+ # Nested object keys whose contents are merged up into the row before primary keys are read+ # (e.g. company ratings nest the rating under a "rating" object).+ flatten_keys: list[str] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["ticker"])+ partition_key: Optional[str] = None # stable date field for datetime partitioning+ should_sync_default: bool = True+++FINNWORLDS_ENDPOINTS: dict[str, FinnworldsEndpointConfig] = {+ "company_information": FinnworldsEndpointConfig(+ name="company_information",+ path="information",+ response_mode=ResponseMode.OUTPUT_OBJECT,+ primary_keys=["ticker"],+ ),+ "income_statements": FinnworldsEndpointConfig(+ name="income_statements",+ path="incomestatements",+ response_mode=ResponseMode.OUTPUT_ARRAY,+ data_key="income_statement",+ include_period=True,+ primary_keys=["ticker", "period", "date"],+ partition_key="date",+ ),+ "balance_sheets": FinnworldsEndpointConfig(+ name="balance_sheets",+ path="balancesheets",+ response_mode=ResponseMode.OUTPUT_ARRAY,+ data_key="balance_sheet",+ include_period=True,+ primary_keys=["ticker", "period", "date"],+ partition_key="date",+ ),+ "cash_flows": FinnworldsEndpointConfig(+ name="cash_flows",+ path="cashflows",+ response_mode=ResponseMode.OUTPUT_ARRAY,+ data_key="cash_flow",+ include_period=True,+ primary_keys=["ticker", "period", "date"],+ partition_key="date",+ ),+ "financial_ratios": FinnworldsEndpointConfig(+ name="financial_ratios",+ path="financialratios",+ response_mode=ResponseMode.OUTPUT_OBJECT,+ primary_keys=["ticker", "date"],+ partition_key="date",+ ),+ "dividends": FinnworldsEndpointConfig(+ name="dividends",+ path="dividends",+ response_mode=ResponseMode.OUTPUT_ARRAY,+ data_key="dividends",+ primary_keys=["ticker", "date"],+ partition_key="date",+ ),+ "stock_splits": FinnworldsEndpointConfig(+ name="stock_splits",+ path="stocksplits",+ response_mode=ResponseMode.OUTPUT_ARRAY,+ data_key="stocksplits",+ primary_keys=["ticker", "date"],+ partition_key="date",+ ),+ "stock_prices": FinnworldsEndpointConfig(+ name="stock_prices",+ path="historicalcandlestick",+ response_mode=ResponseMode.OUTPUT_ARRAY,+ data_key="daily_stock_data",+ primary_keys=["ticker", "date"],+ partition_key="date",+ ),+ "company_ratings": FinnworldsEndpointConfig(+ name="company_ratings",+ path="companyratings",+ response_mode=ResponseMode.RESULT_KEY,+ data_key="analysts",+ flatten_keys=["rating"],+ # No single natural key — a ticker has many analysts, each with dated ratings.+ primary_keys=["ticker", "analyst_name", "analyst_firm", "date_rating"],+ partition_key="date_rating",+ ),+ "sec_filings": FinnworldsEndpointConfig(+ name="sec_filings",+ path="secfilings",+ response_mode=ResponseMode.TOP_LEVEL,+ data_key="sec_filings",+ # The EDGAR index URL is the most stable unique value per filing.+ primary_keys=["ticker", "url"],+ partition_key="date",+ ),+ "bond_yields": FinnworldsEndpointConfig(+ name="bond_yields",+ path="bonds",+ response_mode=ResponseMode.OUTPUT_BARE,+ requires_ticker=False,+ primary_keys=["country", "type", "datetime"],+ partition_key="datetime",+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(FINNWORLDS_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.pyindex 4992a980a57e..2a3fc2fd00aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/source.py@@ -1,30 +1,138 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.finnworlds import (+ finnworlds_source,+ parse_tickers,+ validate_credentials as validate_finnworlds_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.settings import (+ ENDPOINTS,+ FINNWORLDS_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FinnworldsSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass FinnworldsSource(SimpleSource[FinnworldsSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FINNWORLDS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Finnworlds answers an invalid/expired key with HTTP 200 and an error body, which the+ # transport raises as a FinnworldsAuthError carrying this prefix. Retrying can never fix a+ # credential problem, so fail the sync and tell the user to reconnect.+ "Finnworlds authentication failed": "Your Finnworlds API key is invalid or expired, or it lacks access to this dataset. Generate a new key and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: FinnworldsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Finnworlds exposes no server-side update cursor, so every endpoint is full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=FINNWORLDS_ENDPOINTS[endpoint].should_sync_default,+ )+ 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: FinnworldsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ parse_tickers(config.tickers)+ except ValueError as exc:+ return False, str(exc)++ return validate_finnworlds_credentials(config.api_key)++ def source_for_pipeline(self, config: FinnworldsSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return finnworlds_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ tickers=parse_tickers(config.tickers),+ logger=inputs.logger,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FINNWORLDS,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Finnworlds",- iconPath="/static/services/finnworlds.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Finnworlds API key to pull financial market data into the PostHog Data warehouse.++You can find your API key in your [Finnworlds dashboard](https://finnworlds.com/dashboard/).++Most datasets (fundamentals, prices, dividends, ratings) return data for one company per request, so enter the stock tickers you want to sync — the connector fetches each dataset for every ticker. Bond yields are global and ignore the ticker list.""",+ iconPath="/static/services/finnworlds.png",+ docsUrl="https://posthog.com/docs/cdp/sources/finnworlds",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="tickers",+ label="Tickers",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="AAPL, MSFT, GOOGL",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds.pynew file mode 100644index 000000000000..b84bcd49be5a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds.py@@ -0,0 +1,329 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds import finnworlds+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.finnworlds import (+ FinnworldsAuthError,+ FinnworldsRetryableError,+ _build_url,+ _extract_rows,+ _normalize_row,+ _payload_error,+ finnworlds_source,+ get_rows,+ parse_tickers,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.settings import (+ FINNWORLDS_ENDPOINTS,+ FinnworldsEndpointConfig,+ ResponseMode,+)+++def _logger() -> MagicMock:+ return MagicMock()+++def _response(json_body: Any, status_code: int = 200) -> MagicMock:+ resp = MagicMock()+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.json.return_value = json_body++ def _raise() -> None:+ if status_code >= 400:+ raise requests.HTTPError(f"{status_code} error", response=resp)++ resp.raise_for_status.side_effect = _raise+ return resp+++def _session_returning(*responses: MagicMock) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = list(responses)+ return session+++class TestParseTickers:+ @parameterized.expand(+ [+ ("comma_separated", "AAPL,MSFT,GOOGL", ["AAPL", "MSFT", "GOOGL"]),+ ("space_separated", "AAPL MSFT", ["AAPL", "MSFT"]),+ ("newline_separated", "AAPL\nMSFT", ["AAPL", "MSFT"]),+ ("mixed_separators", "aapl, msft\n googl", ["AAPL", "MSFT", "GOOGL"]),+ ("lowercase_uppercased", "aapl", ["AAPL"]),+ ("dedupes_preserving_order", "AAPL, MSFT, AAPL", ["AAPL", "MSFT"]),+ ("strips_whitespace", " AAPL ", ["AAPL"]),+ ("empty_string", "", []),+ ("none", None, []),+ ("only_separators", " , , ", []),+ ]+ )+ def test_parse_tickers(self, _name: str, raw: str | None, expected: list[str]) -> None:+ assert parse_tickers(raw) == expected++ def test_at_max_tickers_is_allowed(self) -> None:+ raw = ",".join(f"T{i}" for i in range(finnworlds.MAX_TICKERS))+ assert len(parse_tickers(raw)) == finnworlds.MAX_TICKERS++ def test_over_max_tickers_is_rejected(self) -> None:+ # Bounds the per-sync outbound fan-out (one request per ticker per table).+ raw = ",".join(f"T{i}" for i in range(finnworlds.MAX_TICKERS + 1))+ with pytest.raises(ValueError, match="Too many tickers"):+ parse_tickers(raw)+++class TestBuildUrl:+ def test_includes_key_and_ticker(self) -> None:+ url = _build_url("incomestatements", {"key": "secret", "ticker": "AAPL"})+ assert url.startswith("https://api.finnworlds.com/api/v1/incomestatements?")+ assert "key=secret" in url+ assert "ticker=AAPL" in url++ def test_url_encodes_values(self) -> None:+ url = _build_url("bonds", {"key": "a b&c"})+ # urlencode escapes the space and ampersand so they don't break the query string.+ assert "a+b%26c" in url+++class TestPayloadError:+ @parameterized.expand(+ [+ ("error_key", {"error": "Invalid key"}, "Invalid key"),+ ("error_key_403", {"error": "403 Forbidden"}, "403 Forbidden"),+ ("status_non_200", {"status": {"code": 401, "message": "Unauthorized"}}, "Unauthorized"),+ ("ok_status", {"status": {"code": 200, "message": "OK"}, "result": {}}, None),+ ("no_error", {"result": {"output": []}}, None),+ ("blank_error_ignored", {"error": " "}, None),+ ]+ )+ def test_payload_error(self, _name: str, payload: dict, expected: str | None) -> None:+ assert _payload_error(payload) == expected+++class TestExtractRows:+ def test_output_array(self) -> None:+ payload = {"result": {"basics": {"ticker": "AAPL"}, "output": {"income_statement": [{"date": "2025-03-31"}]}}}+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["income_statements"])+ assert rows == [{"date": "2025-03-31"}]++ def test_output_object(self) -> None:+ payload = {"result": {"output": {"pe_ratio": "30", "date": "2025-06-01"}}}+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["financial_ratios"])+ assert rows == [{"pe_ratio": "30", "date": "2025-06-01"}]++ def test_output_object_empty_yields_nothing(self) -> None:+ payload: dict[str, Any] = {"result": {"output": {}}}+ assert _extract_rows(payload, FINNWORLDS_ENDPOINTS["financial_ratios"]) == []++ def test_output_bare(self) -> None:+ payload = {"result": {"output": [{"country": "US", "type": "10Y"}]}}+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["bond_yields"])+ assert rows == [{"country": "US", "type": "10Y"}]++ def test_result_key(self) -> None:+ payload = {"result": {"analysts": [{"analyst_name": "Jane"}]}}+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["company_ratings"])+ assert rows == [{"analyst_name": "Jane"}]++ def test_top_level(self) -> None:+ payload = {"sec_filings": [{"url": "https://sec.gov/x"}]}+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["sec_filings"])+ assert rows == [{"url": "https://sec.gov/x"}]++ @parameterized.expand(+ [+ ("missing_result", {}),+ ("output_wrong_shape", {"result": {"output": "not-a-list"}}),+ ("non_dict_rows_filtered", {"result": {"output": {"income_statement": ["str", {"date": "x"}]}}}),+ ]+ )+ def test_malformed_responses_degrade_gracefully(self, _name: str, payload: dict) -> None:+ # Shapes are doc-derived, not curl-verified, so the extractor must never raise on a surprise.+ rows = _extract_rows(payload, FINNWORLDS_ENDPOINTS["income_statements"])+ assert all(isinstance(r, dict) for r in rows)+++class TestNormalizeRow:+ def test_injects_ticker(self) -> None:+ row = _normalize_row({"date": "2025-03-31"}, FINNWORLDS_ENDPOINTS["dividends"], "AAPL", None)+ assert row["ticker"] == "AAPL"++ def test_injects_period(self) -> None:+ row = _normalize_row({"date": "2025-03-31"}, FINNWORLDS_ENDPOINTS["income_statements"], "AAPL", "quarterly")+ assert row["ticker"] == "AAPL"+ assert row["period"] == "quarterly"++ def test_period_defaults_to_annual(self) -> None:+ row = _normalize_row({"date": "2025-03-31"}, FINNWORLDS_ENDPOINTS["income_statements"], "AAPL", None)+ assert row["period"] == "annual"++ def test_flattens_nested_rating(self) -> None:+ raw = {"analyst_name": "Jane", "rating": {"date_rating": "2025-01-01", "price_target": "200"}}+ row = _normalize_row(raw, FINNWORLDS_ENDPOINTS["company_ratings"], "AAPL", None)+ assert row["date_rating"] == "2025-01-01"+ assert row["price_target"] == "200"+ assert row["ticker"] == "AAPL"+ assert "rating" not in row++ def test_no_ticker_injection_for_bonds(self) -> None:+ row = _normalize_row({"country": "US"}, FINNWORLDS_ENDPOINTS["bond_yields"], None, None)+ assert "ticker" not in row+++class TestGetRows:+ def test_ticker_fanout_yields_per_ticker_with_ticker_injected(self) -> None:+ responses = [+ _response({"result": {"output": {"dividends": [{"date": "2025-01-01", "dividend_rate": "0.5"}]}}}),+ _response({"result": {"output": {"dividends": [{"date": "2025-02-01", "dividend_rate": "0.6"}]}}}),+ ]+ session = _session_returning(*responses)+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ batches = list(get_rows("key", "dividends", ["AAPL", "MSFT"], _logger()))++ assert len(batches) == 2+ assert batches[0][0]["ticker"] == "AAPL"+ assert batches[1][0]["ticker"] == "MSFT"++ def test_non_ticker_endpoint_single_fetch(self) -> None:+ session = _session_returning(_response({"result": {"output": [{"country": "US", "type": "10Y"}]}}))+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ batches = list(get_rows("key", "bond_yields", ["AAPL"], _logger()))++ assert session.get.call_count == 1+ assert batches == [[{"country": "US", "type": "10Y"}]]++ def test_auth_error_in_body_raises(self) -> None:+ session = _session_returning(_response({"error": "Invalid key"}))+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ with pytest.raises(FinnworldsAuthError):+ list(get_rows("bad", "dividends", ["AAPL"], _logger()))++ def test_non_auth_error_skips_ticker(self) -> None:+ # First ticker has no data (non-auth error), second succeeds — the sync continues.+ responses = [+ _response({"error": "No data found"}),+ _response({"result": {"output": {"dividends": [{"date": "2025-02-01"}]}}}),+ ]+ session = _session_returning(*responses)+ logger = _logger()+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ batches = list(get_rows("key", "dividends", ["AAPL", "MSFT"], logger))++ assert len(batches) == 1+ assert batches[0][0]["ticker"] == "MSFT"+ logger.warning.assert_called()++ def test_empty_ticker_list_yields_nothing(self) -> None:+ session = _session_returning()+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ batches = list(get_rows("key", "dividends", [], _logger()))+ assert batches == []+ session.get.assert_not_called()+++class TestRetryClassification:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_status_raises_retryable(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _response({}, status_code=status_code)+ with pytest.MonkeyPatch.context() as mp:+ # Don't actually sleep between the bounded retries — keep the test fast.+ mp.setattr(finnworlds._fetch.retry, "sleep", lambda *_: None) # type: ignore[attr-defined]+ with pytest.raises(FinnworldsRetryableError):+ finnworlds._fetch(session, "https://api.finnworlds.com/api/v1/bonds?key=k", _logger())+ # Exhausts the bounded attempts rather than giving up after one try.+ assert session.get.call_count == 5++ def test_http_error_redacts_api_key(self) -> None:+ # A 4xx raises through raise_for_status, whose message embeds the request URL (with ?key=...).+ # The key must never reach the re-raised error that lands in job logs / stored errors.+ resp = MagicMock()+ resp.status_code = 401+ resp.ok = False+ resp.raise_for_status.side_effect = requests.HTTPError(+ "401 Client Error: Unauthorized for url: "+ "https://api.finnworlds.com/api/v1/information?key=SUPERSECRETKEY&ticker=AAPL",+ response=resp,+ )+ session = MagicMock()+ session.get.return_value = resp+ with pytest.raises(requests.HTTPError) as exc_info:+ finnworlds._fetch(session, "https://api.finnworlds.com/api/v1/information?key=SUPERSECRETKEY", _logger())++ message = str(exc_info.value)+ assert "SUPERSECRETKEY" not in message+ assert "key=REDACTED" in message+ # The host prefix is preserved so get_non_retryable_errors() matching still works.+ assert "api.finnworlds.com" in message+++class TestValidateCredentials:+ def test_valid_key(self) -> None:+ session = _session_returning(_response({"result": {"output": {"name": "Apple"}}}))+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ assert validate_credentials("good") == (True, None)++ def test_invalid_key_body(self) -> None:+ session = _session_returning(_response({"error": "Invalid key"}))+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ valid, message = validate_credentials("bad")+ assert valid is False+ assert message == "Invalid Finnworlds API key"++ def test_network_error_reports_distinctly_from_bad_key(self) -> None:+ # A transient connection failure during setup must not be reported as an invalid key.+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(finnworlds, "make_tracked_session", lambda **_: session)+ valid, message = validate_credentials("any")+ assert valid is False+ assert message is not None+ assert "Invalid" not in message+ assert "reach the Finnworlds API" in message+++class TestFinnworldsSource:+ @parameterized.expand([(name,) for name in FINNWORLDS_ENDPOINTS])+ def test_source_response_primary_keys_and_partitioning(self, endpoint: str) -> None:+ config: FinnworldsEndpointConfig = FINNWORLDS_ENDPOINTS[endpoint]+ response = finnworlds_source("key", endpoint, ["AAPL"], _logger())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_partition_keys_are_stable_date_fields(self) -> None:+ # Guard against picking an update-style field that rewrites partitions every sync.+ for config in FINNWORLDS_ENDPOINTS.values():+ if config.partition_key:+ assert "updated" not in config.partition_key+ assert "last" not in config.partition_key++ def test_fundamentals_primary_key_includes_ticker_and_period(self) -> None:+ # The id is not globally unique — fan-out aggregates many tickers, so the key must disambiguate.+ for name in ("income_statements", "balance_sheets", "cash_flows"):+ assert FINNWORLDS_ENDPOINTS[name].primary_keys == ["ticker", "period", "date"]++ def test_all_response_modes_are_covered_by_an_endpoint(self) -> None:+ used = {c.response_mode for c in FINNWORLDS_ENDPOINTS.values()}+ assert used == set(ResponseMode)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds_source.pynew file mode 100644index 000000000000..b4c0b63b229b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnworlds/tests/test_finnworlds_source.py@@ -0,0 +1,138 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.finnworlds import MAX_TICKERS+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.settings import (+ ENDPOINTS,+ FINNWORLDS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.finnworlds.source import FinnworldsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FinnworldsSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = overrides.get("schema_name", "dividends")+ inputs.logger = overrides.get("logger", mock.MagicMock())+ return inputs+++class TestFinnworldsSource:+ def setup_method(self) -> None:+ self.source = FinnworldsSource()+ self.team_id = 123+ self.config = FinnworldsSourceConfig(api_key="fw-test", tickers="AAPL, MSFT")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FINNWORLDS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Finnworlds"+ assert config.label == "Finnworlds"+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/finnworlds"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "tickers"]++ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ tickers_field = config.fields[1]+ assert isinstance(tickers_field, SourceFieldInputConfig)+ assert tickers_field.type == SourceFieldInputConfigType.TEXTAREA+ assert tickers_field.required is True+ assert tickers_field.secret is False++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_matches_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", sorted(FINNWORLDS_ENDPOINTS))+ def test_all_schemas_full_refresh_only(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_respects_should_sync_default(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ # Bond yields fan out globally and are heavier, so they're off by default.+ assert schemas["bond_yields"].should_sync_default is False+ assert schemas["dividends"].should_sync_default is True++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["dividends"])+ assert [s.name for s in schemas] == ["dividends"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials=True + static catalog → public docs can list tables.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ def test_validate_credentials_success(self) -> None:+ with mock.patch.object(source_module, "validate_finnworlds_credentials", return_value=(True, None)):+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)++ def test_validate_credentials_failure(self) -> None:+ with mock.patch.object(+ source_module, "validate_finnworlds_credentials", return_value=(False, "Invalid Finnworlds API key")+ ):+ ok, message = self.source.validate_credentials(self.config, self.team_id)+ assert ok is False+ assert message is not None++ def test_validate_credentials_rejects_oversized_ticker_list(self) -> None:+ # Too many tickers is rejected at setup without ever probing the API, bounding outbound fan-out.+ config = FinnworldsSourceConfig(api_key="fw-test", tickers=",".join(f"T{i}" for i in range(MAX_TICKERS + 1)))+ with mock.patch.object(source_module, "validate_finnworlds_credentials") as probe:+ ok, message = self.source.validate_credentials(config, self.team_id)+ assert ok is False+ assert message is not None+ assert "Too many tickers" in message+ probe.assert_not_called()++ def test_get_non_retryable_errors_includes_auth(self) -> None:+ errors = self.source.get_non_retryable_errors()+ assert "Finnworlds authentication failed" in errors++ def test_get_canonical_descriptions_keyed_by_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "income_statements" in descriptions++ def test_source_for_pipeline_plumbs_parsed_tickers(self) -> None:+ inputs = _make_inputs(schema_name="dividends")+ with mock.patch.object(source_module, "finnworlds_source") as mocked:+ self.source.source_for_pipeline(self.config, inputs)++ mocked.assert_called_once()+ _, kwargs = mocked.call_args+ assert kwargs["api_key"] == "fw-test"+ assert kwargs["endpoint"] == "dividends"+ assert kwargs["tickers"] == ["AAPL", "MSFT"]+ assert kwargs["logger"] is inputs.loggerdiff --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 601db1470793..bb4fe39f4c4a 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@@ -1137,7 +1137,8 @@ class FinnhubSourceConfig(config.Config):@config.configclass FinnworldsSourceConfig(config.Config):- pass+ api_key: str+ tickers: str@config.config