: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(fireworks_ai): sync usage, routers, dpo jobs and rft steps (#107414)
Tom Owers3cc72d639600
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 3ecc906363bf..39e34a332d49 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -3180,16 +3180,16 @@ Note: The repo already carries products/warehouse_sources/backend/temporal/data_## FireworksAI — gaps-Today (10): `batch_inference_jobs`, `datasets`, `deployed_models`, `deployments`, `evaluation_jobs`, `evaluators`, `models`, `reinforcement_fine_tuning_jobs`, `supervised_fine_tuning_jobs`, `users`+Today (14): `account_usage`, `batch_inference_jobs`, `datasets`, `deployed_models`, `deployments`, `dpo_jobs`, `evaluation_jobs`, `evaluators`, `models`, `reinforcement_fine_tuning_jobs`, `reinforcement_fine_tuning_steps`, `routers`, `supervised_fine_tuning_jobs`, `users`Diffed against: <https://docs.fireworks.ai/llms.txt>-- [ ] `GET /v1/accounts/{account_id}/usage (Get Account Usage)` — per-model token and spend usage, the headline analytical metric for an inference platform (high)-- [ ] `GET /v1/accounts/{account_id}/dpoJobs (List dpo jobs)` — a whole fine-tuning job type missing alongside the already-synced supervised and reinforcement jobs (high)-- [ ] `List Reinforcement Fine-tuning Steps` — per-step training progression under each RFT job, the state history behind job outcomes (high)+- [x] `GET /v1/accounts/{account_id}/usage (Get Account Usage)` — per-model token and spend usage, the headline analytical metric for an inference platform (high)+- [x] `GET /v1/accounts/{account_id}/dpoJobs (List dpo jobs)` — a whole fine-tuning job type missing alongside the already-synced supervised and reinforcement jobs (high)+- [x] `List Reinforcement Fine-tuning Steps` — per-step training progression under each RFT job, the state history behind job outcomes (high)- [ ] `List Responses` — stored inference response records - the closest thing to an event table this API offers (medium)- [ ] `Get billing summary` — account-level cost roll-up complementing raw usage (medium)-- [ ] `List Routers` — router definitions that requests are attributed to; needed to interpret usage by route (medium)+- [x] `List Routers` — router definitions that requests are attributed to; needed to interpret usage by route (medium)- [ ] `List Deployment Shapes Versions` — lookup resolving the hardware shape referenced by every synced deployment row (medium)- [ ] `List Accounts` — lookup resolving the account each synced resource is namespaced under, for multi-account orgs (low)- [ ] `List Quotas` — quota limits to compare against observed usage (low)diff --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.pyindex 7bdd8d361886..3354f1b503f9 100644--- 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.py@@ -80,6 +80,25 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"public": "Whether the deployed model is publicly reachable.",},},+ "routers": {+ "description": "Routers in your Fireworks AI account. A router distributes inference traffic across deployments for A/B testing, traffic migration, and load distribution, and is what a request's model alias resolves to.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-routers",+ "columns": {+ "name": "Unique resource name of the router, e.g. accounts/my-account/routers/my-router.",+ "displayName": "Human-readable display name of the router.",+ "createTime": "When the router was created.",+ "createdBy": "Identity of the user who created the router.",+ "state": "Lifecycle state of the router (CREATING, READY, UPDATING, DELETING).",+ "status": "Code and message describing the latest operation's outcome.",+ "deployments": "Resource names of the deployments the router covers.",+ "model": "Resource name of the model requests are routed to. Only set for single-region deployments.",+ "weightedRandom": "Weighted-random routing strategy, when the router uses one.",+ "evenLoad": "Even-load routing strategy, when the router uses one.",+ "aliases": "Alias names that can be used to route requests through this router.",+ "autoGenerated": "Whether Fireworks generated this router for a deployment. Auto-generated routers cannot be updated or deleted.",+ "public": "Whether any account can query the underlying workload, rather than only the owning account.",+ },+ },"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",@@ -121,6 +140,54 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"outputMetrics": "Output metrics of the job.",},},+ "reinforcement_fine_tuning_steps": {+ "description": "Reinforcement fine-tuning steps (RLOR trainer jobs) in your Fireworks AI account. Each row is one training step under a reinforcement fine-tuning job, so the table holds the per-step progression behind a job's outcome.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-reinforcement-fine-tuning-steps",+ "columns": {+ "name": "Unique resource name of the step, e.g. accounts/my-account/rlorTrainerJobs/my-job.",+ "displayName": "Human-readable display name of the step.",+ "createTime": "When the step was created.",+ "completedTime": "When the step 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 step.",+ "dataset": "Resource name of the training dataset.",+ "evaluationDataset": "Resource name of a separate evaluation dataset, if any.",+ "evalAutoCarveout": "Whether the dataset is auto-carved for evaluation.",+ "trainingConfig": "Common training settings (base model, learning rate, LoRA, epochs).",+ "rewardWeights": "Reward metrics used for training, each as <reward_name>=<weight>.",+ "jobProgress": "Progress details for the step.",+ "rolloutDeploymentName": "Deployment the trainer syncs weights to for rollouts, if set.",+ "nodeCount": "Number of nodes used for the step.",+ "acceleratorSeconds": "Accelerator seconds used, keyed by accelerator type (e.g. NVIDIA_H100_80GB).",+ "serviceMode": "Whether the trainer is deployed as a service exposing tinker-style API endpoints.",+ "trainerReplicaCount": "Data-parallel replica count for service-mode trainers.",+ "keepAlive": "Whether the trainer runs in keep-alive mode.",+ "forwardOnly": "Whether the trainer runs forward-only, with no backward or optimizer pass.",+ "inactivityTimeout": "How long the trainer may go without tracked activity before it is stopped automatically.",+ "encryptionState": "CMEK encryption state, stamped at creation.",+ "purpose": "Scheduling purpose for the step.",+ },+ },+ "dpo_jobs": {+ "description": "Preference optimization (DPO and ORPO) fine-tuning jobs in your Fireworks AI account, the third job type alongside supervised and reinforcement fine-tuning.",+ "docs_url": "https://docs.fireworks.ai/api-reference/list-dpo-jobs",+ "columns": {+ "name": "Unique resource name of the DPO job, e.g. accounts/my-account/dpoJobs/my-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 of preferred and non-preferred response pairs.",+ "trainingConfig": "Common training settings (base model, learning rate, LoRA, epochs).",+ "lossConfig": "Loss configuration for the job. Defaults to DPO loss; ORPO when the method is set to ORPO.",+ "wandbConfig": "Weights & Biases account used to log job progress.",+ "purpose": "Scheduling purpose for the job.",+ "useReservation": "Whether the job tries the account's reserved capacity before falling back to shared trainer capacity.",+ },+ },"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",@@ -188,4 +255,34 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"status": "Code and message describing the latest operation's outcome.",},},+ "account_usage": {+ "description": "Daily token and spend usage for your Fireworks AI account, from the billingUsage report. One row is one usage bucket for one day. `usageCategory` names which billed surface the row measures, and the columns a row fills depend on it: serverless rows carry token counts, dedicated rows carry accelerator seconds, and training rows carry whichever the job type bills on.",+ "docs_url": "https://docs.fireworks.ai/api-reference/get-billing-usage",+ "columns": {+ "id": "Synthesized identifier for the bucket, derived from the usage category, the day, and the bucket's dimension fields. Not returned by the API.",+ "usageCategory": "Which billed surface the row measures: serverless, dedicated, or training.",+ "startTime": "Start of the usage bucket. Buckets are aggregated daily, so only the date is meaningful.",+ "endTime": "End of the usage bucket. Buckets are aggregated daily, so only the date is meaningful.",+ "group": "Group-by dimension key-values for the bucket, such as model_name, api_key_id, user_id, or deployment_name.",+ "usageType": "Billing usage type for the bucket, distinguishing inference, deployment, and training kinds.",+ "modelName": 'Model the serverless usage was attributed to. Deprecated by the API in favor of group["model_name"].',+ "apiKeyId": 'API key the serverless usage was attributed to. Deprecated by the API in favor of group["api_key_id"].',+ "promptTokens": "Prompt tokens billed for text inference.",+ "completionTokens": "Completion tokens billed for text inference.",+ "cachedPromptTokens": "Prompt tokens served from cache, a subset of promptTokens.",+ "uncachedPromptTokens": "Prompt tokens not served from cache.",+ "audioInputSeconds": "Audio input seconds billed for audio inference.",+ "costNanoUsd": "Cost in nano-USD (1e-9 USD). 0 when the provider stamps no authoritative cost, which does not mean the usage was free.",+ "deploymentId": "Deployment the dedicated usage was attributed to.",+ "acceleratorType": "GPU or accelerator type billed (e.g. NVIDIA_H100_80GB).",+ "acceleratorSeconds": "Accelerator seconds billed. Divide by 3600 for GPU hours.",+ "placement": "Where the deployment ran (e.g. US_IOWA_1, GLOBAL, US, EUROPE).",+ "baseModel": "Base model of the deployment or training job, when known.",+ "jobId": "Managed training job the usage was attributed to. Empty for serverless training token rows.",+ "trainingSessionId": "Serverless training session the usage was attributed to. Empty for managed training jobs.",+ "jobType": "Kind of training job (sft, dpo, rft, trainer).",+ "tokens": "Total tokens billed for the training bucket. 0 for accelerator-second usage types.",+ "annotations": "Custom annotations carried on the usage, such as team, project, or environment.",+ },+ },}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.mdxindex 1966b291afee..24264f679532 100644--- 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.mdx@@ -24,10 +24,10 @@ 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).+Linking it as a source syncs your platform data into the PostHog Data warehouse: models, datasets,+deployments, routers, fine-tuning jobs, batch inference jobs, evaluations, account users, and your+token and spend usage. You can then join it with your product data, for example to compare what a+feature costs you in inference against how much it gets used.## Prerequisites@@ -51,11 +51,17 @@ To connect Fireworks AI, you need:<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.+Most Fireworks AI endpoints list a collection and page with an opaque page token. They don't expose+a verified server-side "updated since" filter, so those tables sync as a **full refresh**: each sync+re-reads the collection and merges on the primary key. The collections are small per account, so a+full refresh is cheap.++`account_usage` is the exception. It comes from the billing usage report, which takes a date range,+so it supports **incremental** sync and each run only asks for the days it hasn't loaded yet. The+first sync loads the past year. Fireworks keeps restating a day's usage until that day closes, so+every run re-reads the most recent day and merges the updated numbers into the existing rows.++Schedule syncs at a cadence that fits how often your Fireworks AI activity changes.## Configurationdiff --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.pyindex b6a7fb6c34be..334f4939cf3c 100644--- 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.py@@ -1,7 +1,11 @@import re-import dataclasses+import hashlib+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedeltafrom typing import Any, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,@@ -13,20 +17,58 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.settings import (+ ACCOUNT_USAGE,FIREWORKS_AI_ENDPOINTS,PAGE_SIZE,+ USAGE_BACKFILL_DAYS,+ USAGE_MAX_WINDOW_DAYS,+ FireworksAIEndpointConfig,)FIREWORKS_AI_BASE_URL = "https://api.fireworks.ai/v1"_ACCOUNT_ID_REGEX = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")+# The billingUsage response splits its buckets across three arrays, one per billed surface, each+# with its own field set. They become one table keyed on a synthesized `id`, with `usageCategory`+# naming which array a row came from.+_USAGE_CATEGORIES: tuple[tuple[str, str], ...] = (+ ("serverlessCosts", "serverless"),+ ("dedicatedCosts", "dedicated"),+ ("trainingCosts", "training"),+)++# Fields that identify a usage bucket within its category, per the billingUsage response schema.+# Only these, the window and the `group` map feed the synthesized id, never the metric values, so a+# bucket whose metrics are restated between syncs keeps its id and merge updates it in place+# instead of inserting a duplicate.+_USAGE_DIMENSIONS: dict[str, tuple[str, ...]] = {+ "serverless": ("modelName", "usageType", "apiKeyId"),+ "dedicated": ("deploymentId", "acceleratorType", "baseModel", "usageType", "placement"),+ "training": ("jobId", "trainingSessionId", "jobType", "usageType", "acceleratorType", "baseModel"),+}++@frozenclass 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+ page_token: str = ""+ # ISO 8601 start of the first billingUsage window not yet yielded. The usage report paginates+ # by time window rather than page token, so it checkpoints on its own field.+ usage_window_start: str = ""+++@frozen+class UsageWindow:+ """One billingUsage request range. `end` is exclusive, matching the API's endTime."""++ start: datetime+ end: datetime++ def __post_init__(self) -> None:+ if self.start >= self.end:+ raise ValueError(f"Usage window must start before it ends, got {self.start} to {self.end}")def normalize_account_id(account_id: str) -> str:@@ -53,6 +95,147 @@ def _get_headers(api_key: str) -> dict[str, str]:}+def _format_rfc3339(value: datetime) -> str:+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _as_utc_datetime(value: Any) -> datetime:+ """Resolve an incremental watermark to an aware UTC datetime."""+ if isinstance(value, datetime):+ return value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ # datetime subclasses date, so a bare date only reaches here after the check above.+ if isinstance(value, date):+ return datetime(value.year, value.month, value.day, tzinfo=UTC)+ return datetime.fromisoformat(str(value).strip().replace("Z", "+00:00")).astimezone(UTC)+++def _usage_row_id(category: str, item: dict[str, Any]) -> str:+ parts: list[Any] = [category, item.get("startTime"), item.get("endTime")]+ parts.extend(item.get(name) for name in _USAGE_DIMENSIONS[category])+ group = item.get("group")+ if isinstance(group, dict):+ parts.extend(f"{key}={group[key]}" for key in sorted(group))+ # Sentinel for None so a missing dimension cannot collide with an empty-string value.+ joined = "|".join("\x00" if part is None else str(part) for part in parts)+ return hashlib.sha256(joined.encode()).hexdigest()+++def _usage_rows(payload: dict[str, Any]) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for data_key, category in _USAGE_CATEGORIES:+ for item in payload.get(data_key) or []:+ rows.append({**item, "id": _usage_row_id(category, item), "usageCategory": category})+ # The three arrays are ordered independently, and the batcher can split one window across+ # several chunks. The watermark takes the maximum startTime of each chunk it writes, so+ # without this sort a chunk holding the window's newest bucket would advance the watermark+ # past buckets still waiting in a later chunk, and a crash in between would lose them.+ rows.sort(key=lambda row: str(row.get("startTime") or ""))+ return rows+++def _usage_windows(+ db_incremental_field_last_value: Optional[Any],+ now: datetime,+ resume_from: Optional[datetime] = None,+) -> list[UsageWindow]:+ """Resolve the request windows to walk, oldest first.++ A full refresh reaches back `USAGE_BACKFILL_DAYS`; an incremental run starts at the watermark,+ and a resumed run at its checkpoint.+ """+ start = now - timedelta(days=USAGE_BACKFILL_DAYS)+ if db_incremental_field_last_value is not None:+ start = _as_utc_datetime(db_incremental_field_last_value)+ if resume_from is not None:+ start = max(start, resume_from)+ # The newest bucket keeps accumulating until its day closes, so a watermark that has caught up+ # with the clock still has to re-read the current day rather than request an empty window.+ start = min(start, now - timedelta(days=1))++ windows: list[UsageWindow] = []+ while start < now:+ window_end = min(start + timedelta(days=USAGE_MAX_WINDOW_DAYS), now)+ windows.append(UsageWindow(start=start, end=window_end))+ start = window_end+ return windows+++def _fetch_usage_window(session: Any, api_key: str, url: str, window: UsageWindow) -> dict[str, Any]:+ response = session.get(+ url,+ params={"startTime": _format_rfc3339(window.start), "endTime": _format_rfc3339(window.end)},+ headers=_get_headers(api_key),+ timeout=60,+ )+ response.raise_for_status()+ return response.json()+++def _iter_usage_windows(+ api_key: str,+ url: str,+ windows: list[UsageWindow],+ resumable_source_manager: ResumableSourceManager[FireworksAIResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(redact_values=(api_key,))+ for index, window in enumerate(windows):+ yield _usage_rows(_fetch_usage_window(session, api_key, url, window))+ if index + 1 < len(windows):+ # Checkpoint names the first window not yet yielded, so a restart replays at most the+ # window that was in progress and merge dedupes it on the synthesized id.+ resumable_source_manager.save_state(+ FireworksAIResumeConfig(usage_window_start=windows[index + 1].start.isoformat())+ )+++def _resume_usage_window_start(+ resumable_source_manager: ResumableSourceManager[FireworksAIResumeConfig],+) -> Optional[datetime]:+ if not resumable_source_manager.can_resume():+ return None+ resume = resumable_source_manager.load_state()+ if resume is None or not resume.usage_window_start:+ return None+ return _as_utc_datetime(resume.usage_window_start)+++def _source_response(+ endpoint_config: FireworksAIEndpointConfig,+ items: Any,+ column_hints: Any = None,+) -> SourceResponse:+ return SourceResponse(+ name=endpoint_config.name,+ items=items,+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint_config.partition_key],+ column_hints=column_hints,+ )+++def _account_usage_source(+ api_key: str,+ account_id: str,+ endpoint_config: FireworksAIEndpointConfig,+ resumable_source_manager: ResumableSourceManager[FireworksAIResumeConfig],+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ url = f"{FIREWORKS_AI_BASE_URL}/accounts/{normalize_account_id(account_id)}/{endpoint_config.path}"+ windows = _usage_windows(+ db_incremental_field_last_value,+ datetime.now(UTC),+ resume_from=_resume_usage_window_start(resumable_source_manager),+ )+ return _source_response(+ endpoint_config,+ lambda: _iter_usage_windows(api_key, url, windows, resumable_source_manager),+ )++def fireworks_ai_source(api_key: str,account_id: str,@@ -63,6 +246,11 @@ def fireworks_ai_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:endpoint_config = FIREWORKS_AI_ENDPOINTS[endpoint]+ if endpoint == ACCOUNT_USAGE:+ return _account_usage_source(+ api_key, account_id, endpoint_config, resumable_source_manager, db_incremental_field_last_value+ )+path = f"accounts/{normalize_account_id(account_id)}/{endpoint_config.path}"rest_config: RESTAPIConfig = {@@ -114,29 +302,29 @@ def fireworks_ai_source(initial_paginator_state=initial_paginator_state,)- return SourceResponse(- name=endpoint,- items=lambda: resource,- primary_keys=endpoint_config.primary_keys,- partition_count=1,- partition_size=1,- partition_mode="datetime",- partition_format="month",- partition_keys=[endpoint_config.partition_key],- column_hints=resource.column_hints,- )+ return _source_response(endpoint_config, lambda: resource, column_hints=resource.column_hints)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:+ endpoint_config = FIREWORKS_AI_ENDPOINTS.get(endpoint) if endpoint is not None else None+ if endpoint_config is None:# Models is account-scoped and readable by any key — a cheap token + account check.- path = FIREWORKS_AI_ENDPOINTS["models"].path+ endpoint_config = FIREWORKS_AI_ENDPOINTS["models"]++ if endpoint_config.name == ACCOUNT_USAGE:+ # billingUsage rejects a call with no window, so probe the last day instead of asking the+ # collection endpoints' single row.+ now = datetime.now(UTC)+ params: dict[str, Any] = {+ "startTime": _format_rfc3339(now - timedelta(days=1)),+ "endTime": _format_rfc3339(now),+ }+ else:+ params = {"pageSize": 1}- url = f"{FIREWORKS_AI_BASE_URL}/accounts/{normalize_account_id(account_id)}/{path}"+ url = f"{FIREWORKS_AI_BASE_URL}/accounts/{normalize_account_id(account_id)}/{endpoint_config.path}"response = make_tracked_session(redact_values=(api_key,)).get(- url, params={"pageSize": 1}, headers=_get_headers(api_key), timeout=10+ url, params=params, 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.pyindex 79cbb2a35f63..d63b32bd331c 100644--- 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.py@@ -1,4 +1,8 @@-from dataclasses import dataclass, field+from dataclasses import field++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# 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}/@@ -8,26 +12,57 @@ from dataclasses import dataclass, field## 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.+# so every collection table ships full refresh only. Collections are small per account (jobs,+# datasets, deployments), so a full fetch is cheap.+#+# `billingUsage` is the exception to both shapes. It is a report rather than a collection: it takes+# a required startTime/endTime window, does not paginate, and answers with three parallel arrays of+# daily aggregation buckets instead of one keyed collection. Because that window is a documented+# server-side filter, it is the only table here that can sync incrementally.## 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+# Schema name of the billingUsage report. The transport routes it to its own iterator because no+# part of the AIP list shape (collection key, page token, resource `name`) applies to it.+ACCOUNT_USAGE = "account_usage"++# billingUsage rejects a window wider than this ("end_time must not be more than 31 days after+# start_time"), so a backfill walks the requested range in chunks of at most this many days.+USAGE_MAX_WINDOW_DAYS = 31++# How far back the first usage sync reaches when there is no incremental watermark to start from.+# The API documents no history floor, so a year bounds the initial backfill at twelve requests and+# every later run resumes from the watermark instead.+USAGE_BACKFILL_DAYS = 365-@dataclass++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@frozenclass 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+ # Key the row array is nested under in the response (matches the collection segment). None for+ # the billingUsage report, whose three arrays the transport explodes itself.+ data_key: str | None = None# 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.+ # AIP resource names are globally unique full paths, so `name` is the primary key for every+ # collection. The usage report has no resource name and keys on a synthesized `id` instead.primary_keys: list[str] = field(default_factory=lambda: ["name"])+ # Empty unless the endpoint exposes a verified server-side time filter.+ incremental_fields: list[IncrementalField] = field(default_factory=list)FIREWORKS_AI_ENDPOINTS: dict[str, FireworksAIEndpointConfig] = {@@ -37,6 +72,7 @@ FIREWORKS_AI_ENDPOINTS: dict[str, FireworksAIEndpointConfig] = {"deployed_models": FireworksAIEndpointConfig(name="deployed_models", path="deployedModels", data_key="deployedModels"),+ "routers": FireworksAIEndpointConfig(name="routers", path="routers", data_key="routers"),"supervised_fine_tuning_jobs": FireworksAIEndpointConfig(name="supervised_fine_tuning_jobs",path="supervisedFineTuningJobs",@@ -47,6 +83,15 @@ FIREWORKS_AI_ENDPOINTS: dict[str, FireworksAIEndpointConfig] = {path="reinforcementFineTuningJobs",data_key="reinforcementFineTuningJobs",),+ # "List Reinforcement Fine-tuning Steps" in the API reference. The collection is named+ # rlorTrainerJobs after the RLOR trainer that runs each step, so the path and the data key do+ # not resemble the table name.+ "reinforcement_fine_tuning_steps": FireworksAIEndpointConfig(+ name="reinforcement_fine_tuning_steps",+ path="rlorTrainerJobs",+ data_key="rlorTrainerJobs",+ ),+ "dpo_jobs": FireworksAIEndpointConfig(name="dpo_jobs", path="dpoJobs", data_key="dpoJobs"),"batch_inference_jobs": FireworksAIEndpointConfig(name="batch_inference_jobs", path="batchInferenceJobs", data_key="batchInferenceJobs"),@@ -55,6 +100,13 @@ FIREWORKS_AI_ENDPOINTS: dict[str, FireworksAIEndpointConfig] = {),"evaluators": FireworksAIEndpointConfig(name="evaluators", path="evaluators", data_key="evaluators"),"users": FireworksAIEndpointConfig(name="users", path="users", data_key="users"),+ ACCOUNT_USAGE: FireworksAIEndpointConfig(+ name=ACCOUNT_USAGE,+ path="billingUsage",+ partition_key="startTime",+ primary_keys=["id"],+ incremental_fields=[_datetime_incremental_field("startTime")],+ ),}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 eb69161b436b..f46d718bdce4 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@@ -55,7 +55,7 @@ class FireworksAISource(ResumableSource[FireworksAISourceConfig, FireworksAIResucategory=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Fireworks AI",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.+ caption="""Enter your Fireworks AI API key and account ID to sync your models, datasets, deployments, routers, fine-tuning jobs, batch inference jobs, evaluations, account users, and token and spend usage 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",@@ -109,15 +109,16 @@ You can find or create an API key in your [Fireworks AI account settings](https:force_refresh: bool = False,api_version: str | None = None,) -> 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).+ # The list endpoints document an AIP-160 `filter` param but not its filterable fields, and+ # we could not verify server-side timestamp filtering, so every collection is full refresh+ # only. `account_usage` windows on a documented startTime/endTime filter and is the one+ # table that can sync incrementally (see settings.py).schemas = [SourceSchema(name=endpoint,- supports_incremental=False,+ supports_incremental=bool(FIREWORKS_AI_ENDPOINTS[endpoint].incremental_fields),supports_append=False,- incremental_fields=[],+ incremental_fields=FIREWORKS_AI_ENDPOINTS[endpoint].incremental_fields,detected_primary_keys=FIREWORKS_AI_ENDPOINTS[endpoint].primary_keys,)for endpoint in ENDPOINTS@@ -176,5 +177,7 @@ You can find or create an API key in your [Fireworks AI account settings](https:team_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,- db_incremental_field_last_value=None, # every Fireworks AI endpoint is full refresh+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)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.pyindex cfe53cb46f17..deb72ddff6ab 100644--- 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.py@@ -1,7 +1,9 @@import jsonfrom collections.abc import Iterable+from datetime import UTC, datetime, timedeltafrom typing import Any, cast+import pytestfrom unittest import mockfrom parameterized import parameterized@@ -11,13 +13,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.fireworks_ai import (FIREWORKS_AI_BASE_URL,FireworksAIResumeConfig,+ UsageWindow,+ _usage_row_id,+ _usage_rows,+ _usage_windows,fireworks_ai_source,get_status_code,normalize_account_id,)from products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.settings import (+ ACCOUNT_USAGE,FIREWORKS_AI_ENDPOINTS,PAGE_SIZE,+ USAGE_BACKFILL_DAYS,+ USAGE_MAX_WINDOW_DAYS,)# RESTClient builds its session via make_tracked_session in the rest_client module.@@ -132,16 +141,21 @@ class TestPagination:assert rows == [{"name": "m-9"}]assert params[0] == {"pageSize": PAGE_SIZE, "pageToken": "tok-9"}- def test_camel_case_collections_resolve_path_and_data_key(self) -> None:+ @parameterized.expand(+ [+ ("supervised_fine_tuning_jobs", "supervisedFineTuningJobs"),+ # The API calls this collection rlorTrainerJobs, so neither the path nor the data key+ # can be derived from the table name.+ ("reinforcement_fine_tuning_steps", "rlorTrainerJobs"),+ ("dpo_jobs", "dpoJobs"),+ ]+ )+ def test_camel_case_collections_resolve_path_and_data_key(self, endpoint: str, collection: str) -> None:manager = _make_manager()- rows, _params, urls = _rows(- "supervised_fine_tuning_jobs",- [_response({"supervisedFineTuningJobs": [{"name": "sft-1"}]})],- manager,- )+ rows, _params, urls = _rows(endpoint, [_response({collection: [{"name": "row-1"}]})], manager)- assert rows == [{"name": "sft-1"}]- assert urls[0] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/supervisedFineTuningJobs"+ assert rows == [{"name": "row-1"}]+ assert urls[0] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/{collection}"def test_pasted_resource_prefix_does_not_double_the_path(self) -> None:manager = _make_manager()@@ -214,3 +228,245 @@ class TestFireworksAISourceResponse:# don't rewrite on every sync.assert response.partition_keys == [cfg.partition_key]assert response.partition_mode == "datetime"+++_NOW = datetime(2026, 6, 15, 12, 0, tzinfo=UTC)++_SERVERLESS_BUCKET = {+ "startTime": "2026-06-01T00:00:00Z",+ "endTime": "2026-06-02T00:00:00Z",+ "modelName": "accounts/my-account/models/llama",+ "usageType": "TEXT_INFERENCE",+ "apiKeyId": "key-1",+ "group": {"model_name": "accounts/my-account/models/llama"},+ "promptTokens": "100",+ "completionTokens": "20",+}+++class TestUsageWindows:+ def test_full_refresh_walks_the_backfill_in_windows_the_api_accepts(self) -> None:+ windows = _usage_windows(None, _NOW)++ # A window wider than the documented 31 days is rejected outright, so this bound is what+ # keeps a backfill from failing the whole table.+ assert all((w.end - w.start).days <= USAGE_MAX_WINDOW_DAYS for w in windows)+ assert windows[0].start == _NOW - timedelta(days=USAGE_BACKFILL_DAYS)+ assert windows[-1].end == _NOW+ # Contiguous and ascending, so no day falls between two windows.+ assert [w.start for w in windows[1:]] == [w.end for w in windows[:-1]]++ def test_incremental_run_starts_at_the_watermark(self) -> None:+ watermark = _NOW - timedelta(days=40)+ windows = _usage_windows(watermark, _NOW)++ assert windows[0].start == watermark+ assert len(windows) == 2++ @parameterized.expand(+ [+ ("watermark_at_now", timedelta(0)),+ ("watermark_ahead_of_now", timedelta(days=3)),+ ]+ )+ def test_caught_up_watermark_still_re_reads_the_open_day(self, _name: str, offset: timedelta) -> None:+ # The newest bucket keeps accumulating until its day closes. Without the clamp this builds+ # an inverted window, which UsageWindow rejects and the API would 400 on.+ windows = _usage_windows(_NOW + offset, _NOW)++ assert len(windows) == 1+ assert windows[0] == UsageWindow(start=_NOW - timedelta(days=1), end=_NOW)++ def test_resume_checkpoint_skips_windows_already_yielded(self) -> None:+ watermark = _NOW - timedelta(days=90)+ windows = _usage_windows(watermark, _NOW, resume_from=_NOW - timedelta(days=20))++ assert windows[0].start == _NOW - timedelta(days=20)+++class TestUsageRows:+ def test_each_array_becomes_rows_tagged_with_its_category(self) -> None:+ rows = _usage_rows(+ {+ "serverlessCosts": [_SERVERLESS_BUCKET],+ "dedicatedCosts": [{"startTime": "2026-06-01T00:00:00Z", "deploymentId": "dep-1"}],+ "trainingCosts": [{"startTime": "2026-06-01T00:00:00Z", "jobId": "job-1"}],+ }+ )++ assert [row["usageCategory"] for row in rows] == ["serverless", "dedicated", "training"]+ # The API's own fields survive alongside the two synthesized ones.+ assert rows[0]["promptTokens"] == "100"+ assert rows[1]["deploymentId"] == "dep-1"++ @parameterized.expand(+ [+ ("collection_key_omitted", {}),+ ("empty_arrays", {"serverlessCosts": [], "dedicatedCosts": [], "trainingCosts": []}),+ ("null_array", {"serverlessCosts": None}),+ ]+ )+ def test_window_with_no_usage_yields_no_rows(self, _name: str, payload: dict[str, Any]) -> None:+ assert _usage_rows(payload) == []++ def test_rows_arrive_in_ascending_start_time_order(self) -> None:+ # SourceResponse declares sort_mode="asc", and the batcher can split one window across+ # several chunks. If a chunk carried the window's newest bucket the watermark would+ # advance past buckets still queued behind it, and a crash would lose them.+ rows = _usage_rows(+ {+ "serverlessCosts": [+ {**_SERVERLESS_BUCKET, "startTime": "2026-06-03T00:00:00Z"},+ {**_SERVERLESS_BUCKET, "startTime": "2026-06-01T00:00:00Z"},+ ],+ "dedicatedCosts": [{"startTime": "2026-06-02T00:00:00Z", "deploymentId": "dep-1"}],+ }+ )++ assert [row["startTime"] for row in rows] == [+ "2026-06-01T00:00:00Z",+ "2026-06-02T00:00:00Z",+ "2026-06-03T00:00:00Z",+ ]+++class TestUsageRowId:+ def test_restated_metrics_keep_the_same_id(self) -> None:+ # Fireworks restates a day's bucket while it is still open. A metric-sensitive id would+ # insert a second row for the same bucket on every sync instead of merging onto it.+ restated = {**_SERVERLESS_BUCKET, "promptTokens": "999", "completionTokens": "480"}++ assert _usage_row_id("serverless", restated) == _usage_row_id("serverless", _SERVERLESS_BUCKET)++ @parameterized.expand(+ [+ ("start_time", {"startTime": "2026-06-02T00:00:00Z"}),+ ("model_name", {"modelName": "accounts/my-account/models/mixtral"}),+ ("usage_type", {"usageType": "IMAGE_INFERENCE"}),+ ("api_key_id", {"apiKeyId": "key-2"}),+ ("group_dimension", {"group": {"model_name": "accounts/my-account/models/llama", "user_id": "u-1"}}),+ # A dimension the API omits must not hash the same as one it returns empty, or two+ # distinct buckets collapse onto one row.+ ("absent_dimension", {"apiKeyId": None}),+ ("empty_dimension", {"apiKeyId": ""}),+ ]+ )+ def test_each_dimension_produces_a_distinct_id(self, _name: str, override: dict[str, Any]) -> None:+ assert _usage_row_id("serverless", {**_SERVERLESS_BUCKET, **override}) != _usage_row_id(+ "serverless", _SERVERLESS_BUCKET+ )++ def test_group_key_order_does_not_change_the_id(self) -> None:+ # Proto3 JSON gives no map ordering guarantee, so an order-sensitive id would re-key every+ # row whenever the server happened to serialize the map differently.+ one = {**_SERVERLESS_BUCKET, "group": {"model_name": "llama", "user_id": "u-1"}}+ other = {**_SERVERLESS_BUCKET, "group": {"user_id": "u-1", "model_name": "llama"}}++ assert _usage_row_id("serverless", one) == _usage_row_id("serverless", other)++ def test_categories_do_not_share_ids(self) -> None:+ bucket = {"startTime": "2026-06-01T00:00:00Z", "endTime": "2026-06-02T00:00:00Z"}++ assert _usage_row_id("serverless", bucket) != _usage_row_id("dedicated", bucket)+++def _run_usage(+ manager: mock.MagicMock,+ payloads: list[dict[str, Any]],+ db_incremental_field_last_value: Any = None,+) -> tuple[list[dict[str, Any]], list[mock.MagicMock]]:+ session = mock.MagicMock()+ session.get.side_effect = [mock.MagicMock(**{"json.return_value": payload}) for payload in payloads]++ with mock.patch.object(fireworks_ai, "make_tracked_session", return_value=session):+ source_response = fireworks_ai_source(+ api_key="fw_test",+ account_id="my-account",+ endpoint=ACCOUNT_USAGE,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ rows = [row for batch in cast("Iterable[Any]", source_response.items()) for row in batch]+ return rows, session.get.call_args_list+++class TestAccountUsageTransport:+ def test_each_window_is_requested_as_an_explicit_rfc3339_range(self) -> None:+ watermark = datetime.now(UTC) - timedelta(days=40)+ _rows_out, calls = _run_usage(_make_manager(), [{}, {}], db_incremental_field_last_value=watermark)++ assert len(calls) == 2+ assert calls[0].args[0] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/billingUsage"+ # billingUsage has no pageToken; the window is the only thing that moves between calls.+ for call in calls:+ assert set(call.kwargs["params"]) == {"startTime", "endTime"}+ assert call.kwargs["params"]["startTime"].endswith("Z")+ assert calls[0].kwargs["params"]["endTime"] == calls[1].kwargs["params"]["startTime"]+ assert calls[0].kwargs["headers"]["Authorization"] == "Bearer fw_test"++ def test_full_refresh_requests_the_backfill_rather_than_a_watermark(self) -> None:+ _rows_out, calls = _run_usage(_make_manager(), [{}] * 12)++ assert len(calls) == 12++ def test_checkpoint_saved_after_each_window_names_the_next_one(self) -> None:+ manager = _make_manager()+ watermark = datetime.now(UTC) - timedelta(days=40)+ _rows_out, calls = _run_usage(manager, [{}, {}], db_incremental_field_last_value=watermark)++ # One save only: the final window has nothing after it to resume into.+ saved = [call.args[0].usage_window_start for call in manager.save_state.call_args_list]+ assert len(saved) == 1+ # The checkpoint names the first window not yet yielded, so a restart replays at most the+ # window that was in progress.+ # The request param is RFC 3339 to the second, so compare at that resolution.+ assert datetime.fromisoformat(saved[0]).replace(microsecond=0) == datetime.strptime(+ calls[1].kwargs["params"]["startTime"], "%Y-%m-%dT%H:%M:%SZ"+ ).replace(tzinfo=UTC)++ def test_resumes_from_the_saved_window(self) -> None:+ manager = _make_manager(+ FireworksAIResumeConfig(usage_window_start=(datetime.now(UTC) - timedelta(days=5)).isoformat())+ )+ _rows_out, calls = _run_usage(+ manager, [{}], db_incremental_field_last_value=datetime.now(UTC) - timedelta(days=90)+ )++ # Without honouring the checkpoint this would re-walk all 90 days as three windows.+ assert len(calls) == 1++ def test_http_error_propagates_so_the_job_can_classify_it(self) -> None:+ session = mock.MagicMock()+ session.get.return_value.raise_for_status.side_effect = Exception(+ "401 Client Error: Unauthorized for url: https://api.fireworks.ai/v1/accounts/my-account/billingUsage"+ )++ with mock.patch.object(fireworks_ai, "make_tracked_session", return_value=session):+ source_response = fireworks_ai_source(+ api_key="fw_test",+ account_id="my-account",+ endpoint=ACCOUNT_USAGE,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )+ with pytest.raises(Exception, match="401 Client Error"):+ list(cast("Iterable[Any]", source_response.items()))+++class TestAccountUsageStatusProbe:+ def test_probe_sends_a_window_because_billing_usage_rejects_a_bare_call(self) -> None:+ response = mock.MagicMock()+ response.status_code = 200+ session = mock.MagicMock()+ session.get.return_value = response++ with mock.patch.object(fireworks_ai, "make_tracked_session", return_value=session):+ assert get_status_code("fw_test", "my-account", ACCOUNT_USAGE) == 200++ args, kwargs = session.get.call_args+ assert args[0] == f"{FIREWORKS_AI_BASE_URL}/accounts/my-account/billingUsage"+ # A pageSize-only probe would 400 here and read back as a bad API key.+ assert set(kwargs["params"]) == {"startTime", "endTime"}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.pyindex 288554de132b..169aaaa6b40d 100644--- 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.py@@ -6,6 +6,7 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai import source as source_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.fireworks_ai.settings import (+ ACCOUNT_USAGE,ENDPOINTS,FIREWORKS_AI_ENDPOINTS,)@@ -28,13 +29,24 @@ class TestSourceConfig: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_collections_are_full_refresh_and_usage_is_incremental(self) -> None:+ schemas = {s.name: s for s in FireworksAISource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)++ # Server-side timestamp filtering is unverified for the list endpoints (AIP-160 filter+ # fields undocumented), so advertising incremental there would page the whole collection+ # every sync while claiming not to.+ collections = [s for name, s in schemas.items() if name != ACCOUNT_USAGE]+ assert all(s.supports_incremental is False for s in collections)+ assert all(s.incremental_fields == [] for s in collections)++ # billingUsage windows on a required startTime/endTime, which is a real server-side filter.+ usage = schemas[ACCOUNT_USAGE]+ assert usage.supports_incremental is True+ assert [f["field"] for f in usage.incremental_fields] == ["startTime"]++ # Usage buckets are restated while their day is open, so appending would duplicate them.+ assert all(s.supports_append is False for s in schemas.values())def test_names_filter_restricts_output(self) -> None:schemas = FireworksAISource().get_schemas(_config(), team_id=1, names=["models"])