: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 fireworks_ai import source (#70717)
Tom Owersfb9704894349
diff --git a/frontend/public/services/fireworks_ai.svg b/frontend/public/services/fireworks_ai.svgnew file mode 100644index 000000000000..08dfe2b973c9--- /dev/null+++ b/frontend/public/services/fireworks_ai.svg@@ -0,0 +1,5 @@+<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M15.9851 19.1274C15.0969 19.1274 14.2999 18.6001 13.96 17.7838L9.86258 8H12.2608L15.9991 16.9499L19.7339 8H22.1321L18.0102 17.7873C17.6686 18.6001 16.8733 19.1274 15.9851 19.1274Z" fill="#6720FF"/>+<path d="M21.3316 23.8029C20.4469 23.8029 19.6533 23.2792 19.31 22.4698C18.9649 21.6535 19.1436 20.7215 19.7672 20.0891L27.2299 12.5302L28.1618 14.7287L21.3298 21.636L31.068 21.5817L32 23.7802L21.3333 23.8065L21.3298 23.8029H21.3316Z" fill="#6720FF"/>+<path d="M0 23.7766L0.931955 21.5781L10.6702 21.6324L3.83993 14.7234L4.77189 12.5249L12.2345 20.0838C12.8582 20.7145 13.0386 21.65 12.6918 22.4645C12.3484 23.2756 11.5513 23.7977 10.6702 23.7977L0.00350359 23.7731L0 23.7766Z" fill="#6720FF"/>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 004f914bc2f8..d688bb33de60 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -179,6 +179,7 @@ the row lists both.| finnhub | HTTP | requests | ✅ || finnworlds | HTTP | requests | ✅ || firecrawl | HTTP | requests | ✅ |+| fireworks_ai | HTTP | requests | ✅ || fleetio | HTTP | requests | ✅ || firehydrant | HTTP | requests | ✅ || flexmail | HTTP | requests | ✅ |@@ -621,7 +622,6 @@ doesn't conflict with concurrent PRs.- fintoc- firebase- firebolt-- fireworks_ai- flagsmith- flexmail- flexportdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/canonical_descriptions.pynew file mode 100644index 000000000000..7bdd8d361886--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/canonical_descriptions.py@@ -0,0 +1,191 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Fireworks AI API reference (https://docs.fireworks.ai/api-reference).+# Keyed by endpoint name as returned by get_schemas / declared in settings.ENDPOINTS.++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "models": {+ "description": "Models available in your Fireworks AI account, including base models and fine-tuned (PEFT addon) models.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-models",+ "columns": {+ "name": "Unique resource name of the model, e.g. accounts/my-account/models/my-model.",+ "displayName": "Human-readable display name of the model.",+ "description": "Free-text description of the model.",+ "createTime": "When the model was created.",+ "updateTime": "When the model was last updated.",+ "state": "Lifecycle state of the model (UPLOADING, READY).",+ "kind": "Kind of model (e.g. HF_BASE_MODEL, HF_PEFT_ADDON, EMBEDDING_MODEL).",+ "contextLength": "Maximum context length supported by the model.",+ "supportsImageInput": "Whether the model accepts image input.",+ "supportsTools": "Whether the model supports tool/function calling.",+ "supportsLora": "Whether the model supports LoRA addons.",+ "supportsServerless": "Whether the model can be served serverlessly.",+ "fineTuningJob": "Resource name of the fine-tuning job that produced the model, if any.",+ "public": "Whether the model is publicly visible.",+ "deprecationDate": "Date the model is or will be deprecated, if scheduled.",+ },+ },+ "datasets": {+ "description": "Datasets uploaded to or generated in your Fireworks AI account for fine-tuning and evaluation.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-datasets",+ "columns": {+ "name": "Unique resource name of the dataset, e.g. accounts/my-account/datasets/my-dataset.",+ "displayName": "Human-readable display name of the dataset.",+ "createTime": "When the dataset was created.",+ "updateTime": "When the dataset was last updated.",+ "state": "Lifecycle state of the dataset (UPLOADING, READY).",+ "status": "Code and message describing the latest operation's outcome.",+ "exampleCount": "Number of examples in the dataset.",+ "format": "Dataset format (CHAT, COMPLETION, RL).",+ "createdBy": "Identity of the user who created the dataset.",+ "sourceJobName": "Resource name of the job that generated the dataset, if any.",+ "estimatedTokenCount": "Estimated number of tokens in the dataset.",+ },+ },+ "deployments": {+ "description": "Dedicated model deployments in your Fireworks AI account, including autoscaling and hardware configuration.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-deployments",+ "columns": {+ "name": "Unique resource name of the deployment, e.g. accounts/my-account/deployments/my-deployment.",+ "displayName": "Human-readable display name of the deployment.",+ "createTime": "When the deployment was created.",+ "updateTime": "When the deployment was last updated.",+ "state": "Lifecycle state of the deployment (CREATING, READY, DELETING, FAILED, UPDATING, DELETED).",+ "status": "Code and message describing the latest operation's outcome.",+ "baseModel": "Resource name of the model being served.",+ "minReplicaCount": "Autoscaling floor for the number of replicas.",+ "maxReplicaCount": "Autoscaling ceiling for the number of replicas.",+ "replicaCount": "Current number of replicas.",+ "acceleratorCount": "Number of accelerators (GPUs) per replica.",+ "acceleratorType": "Accelerator hardware type (e.g. A100, H100, MI300X).",+ "precision": "Serving precision (e.g. FP16, FP8, BF16).",+ "region": "Region the deployment currently runs in.",+ },+ },+ "deployed_models": {+ "description": "Models loaded onto deployments (including LoRA addons), mapping each model to the deployment serving it.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-deployed-models",+ "columns": {+ "name": "Unique resource name of the deployed model, e.g. accounts/my-account/deployedModels/my-deployed-model.",+ "displayName": "Human-readable display name of the deployed model.",+ "createTime": "When the deployed model was created.",+ "updateTime": "When the deployed model was last updated.",+ "model": "Resource name of the model being deployed.",+ "deployment": "Resource name of the deployment serving the model.",+ "default": "Whether this target is used when the model is queried without a deployment suffix.",+ "state": "Lifecycle state (DEPLOYING, DEPLOYED, UPDATING, UNDEPLOYING).",+ "serverless": "Whether the underlying deployment is managed by Fireworks.",+ "public": "Whether the deployed model is publicly reachable.",+ },+ },+ "supervised_fine_tuning_jobs": {+ "description": "Supervised fine-tuning (SFT) jobs run in your Fireworks AI account, with training configuration and progress.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-supervised-fine-tuning-jobs",+ "columns": {+ "name": "Unique resource name of the fine-tuning job.",+ "displayName": "Human-readable display name of the job.",+ "createTime": "When the job was created.",+ "completedTime": "When the job finished.",+ "updateTime": "When the job was last updated.",+ "state": "Job lifecycle state (e.g. JOB_STATE_RUNNING, JOB_STATE_COMPLETED, JOB_STATE_FAILED).",+ "status": "Code and message describing the latest operation's outcome.",+ "createdBy": "Email of the user who created the job.",+ "dataset": "Resource name of the training dataset.",+ "evaluationDataset": "Resource name of the evaluation dataset, if any.",+ "baseModel": "Resource name of the base model being fine-tuned.",+ "outputModel": "Resource name of the model produced by the job.",+ "epochs": "Number of training epochs.",+ "learningRate": "Training learning rate.",+ "loraRank": "LoRA rank used for training.",+ "jobProgress": "Progress details for the job.",+ "estimatedCost": "Estimated cost of the job.",+ },+ },+ "reinforcement_fine_tuning_jobs": {+ "description": "Reinforcement fine-tuning (RFT) jobs run in your Fireworks AI account, with training/rollout configuration and progress.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-reinforcement-fine-tuning-jobs",+ "columns": {+ "name": "Unique resource name of the reinforcement fine-tuning job.",+ "displayName": "Human-readable display name of the job.",+ "createTime": "When the job was created.",+ "completedTime": "When the job finished.",+ "state": "Job lifecycle state (e.g. running, completed, failed).",+ "status": "Code and message describing the latest operation's outcome.",+ "createdBy": "Email of the user who created the job.",+ "dataset": "Resource name of the training dataset.",+ "evaluator": "Resource name of the evaluator used to score rollouts.",+ "trainingConfig": "Common training settings (base model, learning rate, LoRA, epochs).",+ "jobProgress": "Progress details for the job.",+ "outputMetrics": "Output metrics of the job.",+ },+ },+ "batch_inference_jobs": {+ "description": "Batch inference jobs run in your Fireworks AI account, mapping input datasets to output datasets.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-batch-inference-jobs",+ "columns": {+ "name": "Unique resource name of the batch inference job.",+ "displayName": "Human-readable display name of the job.",+ "createTime": "When the job was created.",+ "updateTime": "When the job was last updated.",+ "state": "Job lifecycle state (e.g. RUNNING, COMPLETED, FAILED).",+ "status": "Code and message describing the latest operation's outcome.",+ "createdBy": "Email of the user who started the job.",+ "model": "Model used for inference.",+ "inputDatasetId": "Dataset supplying the inputs.",+ "outputDatasetId": "Dataset holding the results (also contains the error file).",+ "inferenceParameters": "Sampling settings (maxTokens, temperature, topP, topK, n).",+ "precision": "Serving precision used for the job.",+ "jobProgress": "Progress stats (percent, request counts, token counts, output rows).",+ },+ },+ "evaluation_jobs": {+ "description": "Evaluation jobs run in your Fireworks AI account, scoring a dataset with an evaluator.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-evaluation-jobs",+ "columns": {+ "name": "Unique resource name of the evaluation job.",+ "displayName": "Human-readable display name of the job.",+ "createTime": "When the job was created.",+ "updateTime": "When the job was last updated.",+ "state": "Job lifecycle state (e.g. running, completed, failed).",+ "status": "Code and message describing the latest operation's outcome.",+ "createdBy": "Identity of the user who created the job.",+ "evaluator": "Resource name of the evaluator used.",+ "inputDataset": "Resource name of the input dataset.",+ "outputDataset": "Resource name of the dataset created by the job.",+ "metrics": "Map of metric names to numeric values.",+ },+ },+ "evaluators": {+ "description": "Evaluators defined in your Fireworks AI account, used to score fine-tuning rollouts and evaluation jobs.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-evaluators",+ "columns": {+ "name": "Unique resource name of the evaluator.",+ "displayName": "Human-readable display name of the evaluator.",+ "description": "Free-text description of the evaluator.",+ "createTime": "When the evaluator was created.",+ "updateTime": "When the evaluator was last updated.",+ "createdBy": "Identity of the user who created the evaluator.",+ "state": "Lifecycle state (ACTIVE, BUILDING, BUILD_FAILED).",+ "criteria": "Scoring criteria, each producing a score for its metric.",+ "entryPoint": "Code entry point in module::function or path::function format.",+ "commitHash": "Commit hash from the user's original codebase.",+ },+ },+ "users": {+ "description": "Users and service accounts with access to your Fireworks AI account.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-users",+ "columns": {+ "name": "Unique resource name of the user, e.g. accounts/my-account/users/my-user.",+ "displayName": "Human-readable display name of the user.",+ "createTime": "When the user was added to the account.",+ "updateTime": "When the user was last updated.",+ "email": "Email address of the user.",+ "role": "Role of the user in the account (admin, user, contributor, inference-user, or custom).",+ "serviceAccount": "Whether this user is a service account.",+ "state": "Lifecycle state of the user (CREATING, READY, UPDATING, DELETING).",+ "status": "Code and message describing the latest operation's outcome.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/docs/fireworks-ai.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/docs/fireworks-ai.mdxnew file mode 100644index 000000000000..1966b291afee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/docs/fireworks-ai.mdx@@ -0,0 +1,76 @@+---+title: Linking Fireworks AI as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: FireworksAI+beta: true+---++<!--+This is the user-facing posthog.com source doc. It lives here only because no posthog.com+checkout was available when the source was implemented. Move it to+`posthog.com/contents/docs/cdp/sources/fireworks-ai.mdx` and delete this copy, then run+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.+-->++import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'+import SyncModes from '../_snippets/sync-modes.mdx'+import SourceParameters from '../_snippets/source-parameters.mdx'+import SourceTables from '../_snippets/source-tables.mdx'+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'+import AlphaRelease from '../_snippets/alpha-release.mdx'++<AlphaRelease />++[Fireworks AI](https://fireworks.ai) is an inference and fine-tuning platform for open models.+Linking it as a source syncs your platform data — models, datasets, deployments, fine-tuning jobs,+batch inference jobs, evaluations, and account users — into the PostHog Data warehouse, so you can+join it with your product data (for example, correlating training runs or deployment fleet state+with in-product usage).++## Prerequisites++To connect Fireworks AI, you need:++- A Fireworks AI account.+- An API key generated from your Fireworks AI account settings (used as a bearer token).+- Your Fireworks account ID, shown in your account settings and in every resource name+ (`accounts/<account-id>/...`).++## Adding a data source++<SourceSetupIntro />++1. Open Fireworks AI and go to your [API keys settings](https://app.fireworks.ai/settings/users/api-keys).+2. Create a new API key and copy it.+3. Paste the key into the **API key** field in PostHog.+4. Enter your Fireworks account ID into the **Account ID** field.++## Sync modes++<SyncModes />++Fireworks AI's list endpoints paginate with an opaque page token and don't expose a verified+server-side "updated since" filter, so every table syncs as a **full refresh** — each sync+re-reads the collection and merges on the primary key. These collections are small per account,+so a full refresh is cheap. Schedule syncs at a cadence that fits how often your Fireworks AI+activity changes.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **"Invalid Fireworks AI API key"** when connecting: the key is wrong or has been revoked.+ Generate a new key in your Fireworks AI account settings and re-enter it.+- **"Fireworks AI account not found"** when connecting: the account ID doesn't match the API+ key's account. Copy the account ID from your account settings — it's the segment after+ `accounts/` in any resource name.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/fireworks_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/fireworks_ai.pynew file mode 100644index 000000000000..80b6370fde0d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/fireworks_ai.py@@ -0,0 +1,199 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.settings import (+ FIREWORKS_AI_ENDPOINTS,+ PAGE_SIZE,+)++FIREWORKS_AI_BASE_URL = "https://api.fireworks.ai/v1"++_ACCOUNT_ID_REGEX = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")+++class FireworksAIRetryableError(Exception):+ pass+++class FireworksAIResumeConfig:+ # Opaque nextPageToken from the last committed page. The API requires all other params to+ # match the original call, so the transport re-sends the same pageSize alongside it.+ page_token: str+++def normalize_account_id(account_id: str) -> str:+ """Reduce whatever the user entered to the bare Fireworks account id.++ Users may paste the full resource prefix ("accounts/my-account") shown throughout the+ Fireworks docs and firectl output. Without normalizing, the request path becomes+ /v1/accounts/accounts/my-account/... which can never resolve.+ """+ account_id = account_id.strip().strip("/")+ if account_id.startswith("accounts/"):+ account_id = account_id[len("accounts/") :]+ return account_id+++def is_valid_account_id(account_id: str) -> bool:+ return _ACCOUNT_ID_REGEX.match(account_id) is not None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++@retry(+ retry=retry_if_exception_type(+ (+ FireworksAIRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ url: str,+ params: dict[str, Any] | None,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> Any:+ response = session.get(url, params=params, headers=headers, timeout=60)++ # 429 (rate limit) and 5xx are transient — retry with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise FireworksAIRetryableError(f"Fireworks AI API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Never log response.text or the raw URL: the error body can echo account content and the+ # query string carries pagination tokens. Log only status plus scheme/host/path.+ safe = urlsplit(response.url)+ safe_url = f"{safe.scheme}://{safe.netloc}{safe.path}"+ logger.error("Fireworks AI API error", status=response.status_code, url=safe_url)+ # raise_for_status() would embed the full request URL in the exception, which is surfaced as+ # the schema's latest_error. Rebuild the error from scheme/host/path only. The+ # "<status> Client Error: <reason> for url: https://api.fireworks.ai" prefix stays stable+ # for get_non_retryable_errors() matching.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {safe_url}",+ response=response,+ )++ return response.json()+++def _extract_rows(payload: Any, data_key: str, endpoint: str) -> list[dict[str, Any]]:+ """Unwrap the AIP list envelope: {"<collection>": [...], "nextPageToken": ..., "totalSize": n}.++ Proto3 JSON omits empty repeated fields, so a missing collection key means an empty page,+ not a shape error.+ """+ if not isinstance(payload, dict):+ raise ValueError(f"Unexpected Fireworks AI response shape for endpoint '{endpoint}': {type(payload).__name__}")++ rows = payload.get(data_key, [])+ if not isinstance(rows, list):+ raise ValueError(f"Unexpected Fireworks AI '{data_key}' value for endpoint '{endpoint}': not a list")++ return [row for row in rows if isinstance(row, dict)]+++def get_rows(+ api_key: str,+ account_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FireworksAIResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = FIREWORKS_AI_ENDPOINTS[endpoint]+ # Disable the session's built-in urllib3 retry layer: `_fetch` already retries 429/5xx (via+ # `FireworksAIRetryableError`) and timeouts/connection errors through tenacity. Leaving the+ # default in place would stack retries under tenacity's 5 attempts.+ session = make_tracked_session(redact_values=(api_key,), retry=Retry(total=0))+ headers = _get_headers(api_key)+ url = f"{FIREWORKS_AI_BASE_URL}/accounts/{normalize_account_id(account_id)}/{endpoint_config.path}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page_token: str | None = resume.page_token if resume else None+ if page_token:+ logger.debug("Fireworks AI: resuming from saved page token", endpoint=endpoint)++ while True:+ params: dict[str, Any] = {"pageSize": PAGE_SIZE}+ if page_token:+ params["pageToken"] = page_token++ payload = _fetch(session, url, params, headers, logger)+ rows = _extract_rows(payload, endpoint_config.data_key, endpoint)+ logger.debug("Fireworks AI: fetched page", count=len(rows), endpoint=endpoint)+ if rows:+ yield rows++ next_token = payload.get("nextPageToken")+ if not next_token:+ break+ # Save state after yielding the batch: a crash re-yields the last page (merge dedupes on+ # the primary key) rather than skipping it.+ resumable_source_manager.save_state(FireworksAIResumeConfig(page_token=next_token))+ page_token = next_token+++def fireworks_ai_source(+ api_key: str,+ account_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FireworksAIResumeConfig],+) -> SourceResponse:+ endpoint_config = FIREWORKS_AI_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ account_id=account_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint_config.partition_key],+ )+++def get_status_code(api_key: str, account_id: str, endpoint: str | None = None) -> int:+ """Cheap probe used by credential validation. Returns the HTTP status code."""+ if endpoint is not None and endpoint in FIREWORKS_AI_ENDPOINTS:+ path = FIREWORKS_AI_ENDPOINTS[endpoint].path+ else:+ # Models is account-scoped and readable by any key — a cheap token + account check.+ path = FIREWORKS_AI_ENDPOINTS["models"].path++ url = f"{FIREWORKS_AI_BASE_URL}/accounts/{normalize_account_id(account_id)}/{path}"+ response = make_tracked_session(redact_values=(api_key,)).get(+ url, params={"pageSize": 1}, headers=_get_headers(api_key), timeout=10+ )+ return response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/settings.pynew file mode 100644index 000000000000..79cbb2a35f63--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/settings.py@@ -0,0 +1,60 @@+from dataclasses import dataclass, field++# Fireworks AI control-plane API (https://docs.fireworks.ai/api-reference). A Google AIP-style+# resource API: every collection is a GET under https://api.fireworks.ai/v1/accounts/{account_id}/+# returning {"<collection>": [...], "nextPageToken": "...", "totalSize": n} with pageToken/pageSize+# pagination (pageSize max 200, default 50). Objects carry a globally unique read-only `name`+# (e.g. "accounts/my-account/models/my-model") plus read-only `createTime`/`updateTime`.+#+# The spec documents an AIP-160 `filter` param on every list endpoint, but the filterable fields+# are not enumerated and we could not verify server-side timestamp filtering against the live API,+# so every table ships full refresh only. Collections are small per account (jobs, datasets,+# deployments), so a full fetch is cheap.+#+# The apiKeys collection is deliberately excluded: it is nested per user and its schema carries+# key material (`key`, `prefix`) that must not land in a warehouse table.++PAGE_SIZE = 200+++@dataclass+class FireworksAIEndpointConfig:+ name: str+ # Collection segment under /v1/accounts/{account_id}/, e.g. "supervisedFineTuningJobs".+ path: str+ # Key the row array is nested under in the response (matches the collection segment).+ data_key: str+ # Field to partition Delta files by. Must be a STABLE field (createTime, never updateTime).+ partition_key: str = "createTime"+ # AIP resource names are globally unique full paths, so `name` is the primary key everywhere.+ primary_keys: list[str] = field(default_factory=lambda: ["name"])+++FIREWORKS_AI_ENDPOINTS: dict[str, FireworksAIEndpointConfig] = {+ "models": FireworksAIEndpointConfig(name="models", path="models", data_key="models"),+ "datasets": FireworksAIEndpointConfig(name="datasets", path="datasets", data_key="datasets"),+ "deployments": FireworksAIEndpointConfig(name="deployments", path="deployments", data_key="deployments"),+ "deployed_models": FireworksAIEndpointConfig(+ name="deployed_models", path="deployedModels", data_key="deployedModels"+ ),+ "supervised_fine_tuning_jobs": FireworksAIEndpointConfig(+ name="supervised_fine_tuning_jobs",+ path="supervisedFineTuningJobs",+ data_key="supervisedFineTuningJobs",+ ),+ "reinforcement_fine_tuning_jobs": FireworksAIEndpointConfig(+ name="reinforcement_fine_tuning_jobs",+ path="reinforcementFineTuningJobs",+ data_key="reinforcementFineTuningJobs",+ ),+ "batch_inference_jobs": FireworksAIEndpointConfig(+ name="batch_inference_jobs", path="batchInferenceJobs", data_key="batchInferenceJobs"+ ),+ "evaluation_jobs": FireworksAIEndpointConfig(+ name="evaluation_jobs", path="evaluationJobs", data_key="evaluationJobs"+ ),+ "evaluators": FireworksAIEndpointConfig(name="evaluators", path="evaluators", data_key="evaluators"),+ "users": FireworksAIEndpointConfig(name="users", path="users", data_key="users"),+}++ENDPOINTS = tuple(FIREWORKS_AI_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/source.pyindex fe690a6e88aa..9ac53e4f9316 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/source.py@@ -1,31 +1,175 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.fireworks_ai import (+ FireworksAIResumeConfig,+ fireworks_ai_source,+ get_status_code,+ is_valid_account_id,+ normalize_account_id,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.settings import (+ ENDPOINTS,+ FIREWORKS_AI_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FireworksAISourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FireworksAISource(SimpleSource[FireworksAISourceConfig]):+class FireworksAISource(ResumableSource[FireworksAISourceConfig, FireworksAIResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FIREWORKSAI+ @property+ def connection_host_fields(self) -> list[str]:+ # account_id selects which Fireworks account the stored API key is used against; changing+ # it must require re-entering the secret so a preserved key can't be retargeted at another+ # account the key happens to have access to.+ return ["account_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FIREWORKS_AI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Fireworks AI",- iconPath="/static/services/fireworks_ai.png",- keywords=["llm", "inference", "fine-tuning", "ai"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Fireworks AI API key and account ID to sync your models, datasets, deployments, fine-tuning jobs, batch inference jobs, evaluations, and account users into the PostHog Data warehouse.++You can find or create an API key in your [Fireworks AI account settings](https://app.fireworks.ai/settings/users/api-keys). Your account ID is shown in your account settings and in every resource name (`accounts/<account-id>/...`).""",+ iconPath="/static/services/fireworks_ai.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/fireworks-ai",+ keywords=["fireworks", "llm", "inference", "fine-tuning", "ai"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="my-account",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.canonical_descriptions import ( # noqa: PLC0415 — lazy import per the source architecture contract+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid/revoked key surfaces as a requests HTTPError rebuilt from scheme/host/path+ # (see fireworks_ai._fetch). Match the stable status text and base host.+ "401 Client Error: Unauthorized for url: https://api.fireworks.ai": "Your Fireworks AI API key is invalid or has been revoked. Create a new API key in your Fireworks AI account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.fireworks.ai": "Your Fireworks AI API key does not have permission to access this data. Check that the account ID matches the key's account and that the key has read access, then reconnect.",+ "404 Client Error: Not Found for url: https://api.fireworks.ai": "Fireworks AI could not find this resource. Check that the account ID is correct, then reconnect.",+ }++ def get_schemas(+ self,+ config: FireworksAISourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # The API documents an AIP-160 `filter` param but not its filterable fields, and we could+ # not verify server-side timestamp filtering, so every table is full refresh only+ # (see settings.py).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=FIREWORKS_AI_ENDPOINTS[endpoint].primary_keys,+ )+ 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: FireworksAISourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ account_id = normalize_account_id(config.account_id)+ if not is_valid_account_id(account_id):+ return False, "Fireworks AI account ID is invalid. Copy it from your Fireworks AI account settings."++ try:+ status = get_status_code(config.api_key, account_id, schema_name)+ except Exception:+ return False, "Could not reach the Fireworks AI API. Check your network connection and try again."++ if status == 200:+ return True, None+ if status == 401:+ return (+ False,+ "Invalid Fireworks AI API key. Check the key in your Fireworks AI account settings, then reconnect.",+ )+ if status == 404:+ return False, "Fireworks AI account not found. Check the account ID and try again."+ if status == 403:+ # Accept a valid-but-restricted key at source-create so the user can still sync the+ # tables the key can reach; only fail the per-schema check.+ if schema_name is None:+ return True, None+ return False, f"Your Fireworks AI API key does not have permission to sync '{schema_name}'."+ return False, f"Unexpected response from the Fireworks AI API (status {status})."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FireworksAIResumeConfig]:+ return ResumableSourceManager[FireworksAIResumeConfig](inputs, FireworksAIResumeConfig)++ def source_for_pipeline(+ self,+ config: FireworksAISourceConfig,+ resumable_source_manager: ResumableSourceManager[FireworksAIResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return fireworks_ai_source(+ api_key=config.api_key,+ account_id=config.account_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/tests/test_fireworks_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/tests/test_fireworks_ai.pynew file mode 100644index 000000000000..9965a0ab636c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/tests/test_fireworks_ai.py@@ -0,0 +1,258 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai import fireworks_ai+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.fireworks_ai import (+ FIREWORKS_AI_BASE_URL,+ FireworksAIResumeConfig,+ _extract_rows,+ fireworks_ai_source,+ get_rows,+ get_status_code,+ normalize_account_id,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.settings import (+ FIREWORKS_AI_ENDPOINTS,+ PAGE_SIZE,+)+++def _manager(resume_token: str | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume_token is not None+ manager.load_state.return_value = FireworksAIResumeConfig(page_token=resume_token) if resume_token else None+ return manager+++def _collect(+ monkeypatch: Any, endpoint: str, payloads: list[Any], manager: MagicMock | None = None+) -> tuple[list[dict], list[dict[str, Any]], MagicMock]:+ """Feed successive `payloads` from _fetch and return (rows, recorded fetch calls, manager)."""+ calls: list[dict[str, Any]] = []+ remaining = list(payloads)++ def fake_fetch(session: Any, url: str, params: Any, headers: dict[str, str], logger: Any) -> Any:+ calls.append({"url": url, "params": params, "headers": headers})+ return remaining.pop(0)++ monkeypatch.setattr(fireworks_ai, "_fetch", fake_fetch)+ manager = manager if manager is not None else _manager()++ rows: list[dict] = []+ for batch in get_rows(+ api_key="fw_test",+ account_id="my-account",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ ):+ rows.extend(batch)+ return rows, calls, manager+++class TestNormalizeAccountId:+ @parameterized.expand(+ [+ ("bare_id", "my-account", "my-account"),+ ("resource_prefix", "accounts/my-account", "my-account"),+ ("whitespace_and_slashes", " accounts/my-account/ ", "my-account"),+ ]+ )+ def test_reduces_input_to_bare_account_id(self, _name: str, entered: str, expected: str) -> None:+ assert normalize_account_id(entered) == expected+++class TestExtractRows:+ @parameterized.expand(+ [+ ("rows_present", {"models": [{"name": "m-1"}, {"name": "m-2"}]}, [{"name": "m-1"}, {"name": "m-2"}]),+ # Proto3 JSON omits empty repeated fields — a missing collection key is an empty page.+ ("collection_key_omitted", {"totalSize": 0}, []),+ ("empty_collection", {"models": []}, []),+ ("non_dict_rows_dropped", {"models": ["not-a-row", {"name": "m-1"}]}, [{"name": "m-1"}]),+ ]+ )+ def test_unwraps_aip_list_envelope(self, _name: str, payload: Any, expected: list[dict]) -> None:+ assert _extract_rows(payload, "models", "models") == expected++ @parameterized.expand(+ [+ ("string_body", "error"),+ ("null_body", None),+ ("bare_array", [{"name": "m-1"}]),+ ("collection_not_a_list", {"models": "oops"}),+ ]+ )+ def test_unexpected_shape_raises(self, _name: str, payload: Any) -> None:+ # A silently-swallowed shape change would sync an empty table and look like data loss.+ with pytest.raises(ValueError):+ _extract_rows(payload, "models", "models")+++class TestGetRowsPagination:+ def test_single_page_yields_rows_and_saves_no_state(self, monkeypatch: Any) -> None:+ rows, calls, manager = _collect(monkeypatch, "models", [{"models": [{"name": "m-1"}]}])+ assert rows == [{"name": "m-1"}]+ assert len(calls) == 1+ assert calls[0]["url"] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/models"+ assert calls[0]["params"] == {"pageSize": PAGE_SIZE}+ assert calls[0]["headers"]["Authorization"] == "Bearer fw_test"+ manager.save_state.assert_not_called()++ def test_follows_next_page_token_and_saves_state_after_each_page(self, monkeypatch: Any) -> None:+ rows, calls, manager = _collect(+ monkeypatch,+ "models",+ [+ {"models": [{"name": "m-1"}], "nextPageToken": "tok-2"},+ {"models": [{"name": "m-2"}], "nextPageToken": "tok-3"},+ {"models": [{"name": "m-3"}]},+ ],+ )+ assert rows == [{"name": "m-1"}, {"name": "m-2"}, {"name": "m-3"}]+ assert [c["params"].get("pageToken") for c in calls] == [None, "tok-2", "tok-3"]+ # State is saved after yielding each page, so a crash re-yields the last page rather+ # than skipping it.+ saved = [call.args[0].page_token for call in manager.save_state.call_args_list]+ assert saved == ["tok-2", "tok-3"]++ def test_empty_next_page_token_terminates(self, monkeypatch: Any) -> None:+ _rows, calls, manager = _collect(monkeypatch, "models", [{"models": [{"name": "m-1"}], "nextPageToken": ""}])+ assert len(calls) == 1+ manager.save_state.assert_not_called()++ def test_resumes_from_saved_page_token(self, monkeypatch: Any) -> None:+ rows, calls, _manager_ = _collect(+ monkeypatch, "models", [{"models": [{"name": "m-9"}]}], manager=_manager(resume_token="tok-9")+ )+ assert rows == [{"name": "m-9"}]+ assert calls[0]["params"] == {"pageSize": PAGE_SIZE, "pageToken": "tok-9"}++ def test_camel_case_collections_resolve_path_and_data_key(self, monkeypatch: Any) -> None:+ rows, calls, _manager_ = _collect(+ monkeypatch,+ "supervised_fine_tuning_jobs",+ [{"supervisedFineTuningJobs": [{"name": "sft-1"}]}],+ )+ assert rows == [{"name": "sft-1"}]+ assert calls[0]["url"] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/supervisedFineTuningJobs"++ def test_pasted_resource_prefix_does_not_double_the_path(self, monkeypatch: Any) -> None:+ calls: list[str] = []++ def fake_fetch(session: Any, url: str, params: Any, headers: Any, logger: Any) -> Any:+ calls.append(url)+ return {"models": []}++ monkeypatch.setattr(fireworks_ai, "_fetch", fake_fetch)+ list(+ get_rows(+ api_key="fw_test",+ account_id="accounts/my-account",+ endpoint="models",+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ )+ )+ assert calls[0] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/models"+++class TestFetchRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 500),+ ("bad_gateway", 502),+ ]+ )+ def test_retryable_status_codes_are_retried(self, _name: str, status_code: int) -> None:+ retryable = MagicMock()+ retryable.status_code = status_code+ retryable.ok = False++ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"models": []}++ session = MagicMock()+ session.get.side_effect = [retryable, good]++ with patch.object(fireworks_ai._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = fireworks_ai._fetch(session, f"{FIREWORKS_AI_BASE_URL}/x", None, {}, MagicMock())++ assert result == {"models": []}+ assert session.get.call_count == 2++ def test_client_error_raises_immediately_without_query_string(self) -> None:+ unauthorized = MagicMock()+ unauthorized.status_code = 401+ unauthorized.ok = False+ unauthorized.reason = "Unauthorized"+ unauthorized.url = f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/models?pageToken=tok-secret"++ session = MagicMock()+ session.get.return_value = unauthorized++ with pytest.raises(requests.HTTPError) as exc_info:+ fireworks_ai._fetch(session, f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/models", None, {}, MagicMock())++ # The rebuilt error must not leak the pagination token, and its prefix must stay stable+ # for get_non_retryable_errors() matching.+ message = str(exc_info.value)+ assert "401 Client Error: Unauthorized for url: https://api.fireworks.ai" in message+ assert "pageToken" not in message+ assert session.get.call_count == 1+++class TestGetStatusCode:+ def test_default_probe_hits_models_with_bearer_auth(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response++ with patch.object(fireworks_ai, "make_tracked_session", return_value=session):+ status = get_status_code("fw_test", "my-account")++ assert status == 200+ args, kwargs = session.get.call_args+ assert args[0] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/models"+ assert kwargs["params"] == {"pageSize": 1}+ assert kwargs["headers"]["Authorization"] == "Bearer fw_test"++ def test_schema_probe_hits_that_endpoints_path(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response++ with patch.object(fireworks_ai, "make_tracked_session", return_value=session):+ get_status_code("fw_test", "my-account", "evaluation_jobs")++ args, _kwargs = session.get.call_args+ assert args[0] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/evaluationJobs"+++class TestFireworksAISourceResponse:+ @parameterized.expand(list(FIREWORKS_AI_ENDPOINTS.keys()))+ def test_source_response_uses_endpoint_primary_keys_and_stable_partition(self, endpoint: str) -> None:+ response = fireworks_ai_source(+ api_key="fw_test",+ account_id="my-account",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ )+ cfg = FIREWORKS_AI_ENDPOINTS[endpoint]+ assert response.name == endpoint+ assert response.primary_keys == cfg.primary_keys+ # Partition on the stable creation timestamp — never updateTime — so partitions+ # don't rewrite on every sync.+ assert response.partition_keys == [cfg.partition_key]+ assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/tests/test_fireworks_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/tests/test_fireworks_ai_source.pynew file mode 100644index 000000000000..ea57349f6b89--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/tests/test_fireworks_ai_source.py@@ -0,0 +1,174 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.fireworks_ai import (+ FireworksAIResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.settings import (+ ENDPOINTS,+ FIREWORKS_AI_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.source import FireworksAISource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "fw_test", account_id: str = "my-account") -> Any:+ return source_module.FireworksAISourceConfig(api_key=api_key, account_id=account_id)+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert FireworksAISource().source_type == ExternalDataSourceType.FIREWORKSAI++ def test_config_declares_secret_api_key_and_account_id_fields(self) -> None:+ fields = FireworksAISource().get_source_config.fields+ assert [f.name for f in fields] == ["api_key", "account_id"]+ api_key_field = fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.secret is True+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — required so the public docs render the table list.+ assert FireworksAISource.lists_tables_without_credentials is True++ def test_account_id_change_requires_secret_reentry(self) -> None:+ # Dropping this override would let an editor retarget a preserved API key at another+ # Fireworks account without re-entering it (the update serializer keys off this list).+ assert FireworksAISource().connection_host_fields == ["account_id"]+++class TestGetSchemas:+ def test_returns_all_endpoints_full_refresh_only(self) -> None:+ schemas = FireworksAISource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Server-side timestamp filtering is unverified (AIP-160 filter fields undocumented),+ # so nothing may advertise incremental/append.+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)++ def test_names_filter_restricts_output(self) -> None:+ schemas = FireworksAISource().get_schemas(_config(), team_id=1, names=["models"])+ assert [s.name for s in schemas] == ["models"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = FireworksAISource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ models = next(t for t in tables if t["name"] == "models")+ assert models["primary_keys"] == ["name"]+ assert "Full refresh" in models["sync_methods"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("account_not_found", 404, None, False),+ ("forbidden_at_create_is_accepted", 403, None, True),+ ("forbidden_for_schema_is_rejected", 403, "models", False),+ ("unexpected", 500, None, False),+ ]+ )+ def test_status_code_mapping(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:+ with patch.object(source_module, "get_status_code", return_value=status):+ ok, _err = FireworksAISource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+ assert ok is expected_ok++ def test_invalid_account_id_rejected_without_probe(self) -> None:+ with patch.object(source_module, "get_status_code") as mock_probe:+ ok, err = FireworksAISource().validate_credentials(_config(account_id="bad id!"), team_id=1)+ assert ok is False+ assert err is not None+ mock_probe.assert_not_called()++ def test_pasted_resource_prefix_is_normalized_before_probe(self) -> None:+ with patch.object(source_module, "get_status_code", return_value=200) as mock_probe:+ ok, _err = FireworksAISource().validate_credentials(_config(account_id="accounts/my-account"), team_id=1)+ assert ok is True+ assert mock_probe.call_args.args == ("fw_test", "my-account", None)++ def test_transport_failure_returns_actionable_error(self) -> None:+ with patch.object(source_module, "get_status_code", side_effect=Exception("boom")):+ ok, err = FireworksAISource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert err is not None+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.fireworks.ai/v1/accounts/my-account/models",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.fireworks.ai/v1/accounts/my-account/datasets",+ ),+ (+ "account_not_found",+ "404 Client Error: Not Found for url: https://api.fireworks.ai/v1/accounts/nope/models",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = FireworksAISource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.fireworks.ai/v1/accounts/my-account/models",+ ),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.fireworks.ai/v1/accounts/my-account/models",+ ),+ ("read_timeout", "HTTPSConnectionPool(host='api.fireworks.ai', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_stay_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = FireworksAISource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestSourceForPipeline:+ def test_plumbs_config_schema_and_manager_through(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "models"+ manager = MagicMock()+ with patch.object(source_module, "fireworks_ai_source") as mock_source:+ FireworksAISource().source_for_pipeline(_config(api_key="fw_k", account_id="acct"), manager, inputs)+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "fw_k"+ assert kwargs["account_id"] == "acct"+ assert kwargs["endpoint"] == "models"+ assert kwargs["resumable_source_manager"] is manager++ def test_resumable_source_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ inputs.team_id = 1+ inputs.job_id = "job-1"+ manager = FireworksAISource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FireworksAIResumeConfig+++class TestCanonicalDescriptions:+ def test_every_endpoint_has_a_canonical_description(self) -> None:+ descriptions = FireworksAISource().get_canonical_descriptions()+ for endpoint in FIREWORKS_AI_ENDPOINTS:+ assert endpoint in descriptions+ entry = descriptions[endpoint]+ # Primary key columns must be documented so enrichment doesn't fall back to the LLM for them.+ for pk in FIREWORKS_AI_ENDPOINTS[endpoint].primary_keys:+ assert pk in entry["columns"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 8e4dc7422310..e9f3273b990e 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@@ -1489,7 +1489,8 @@ class FirecrawlSourceConfig(config.Config):@config.configclass FireworksAISourceConfig(config.Config):- pass+ api_key: str+ account_id: str@config.config