Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement openrouter import source (#70031)

Tom Owers11cf7c4b00b9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 63381737d5ec..123da38b482d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -299,6 +299,7 @@ the row lists both.
| orb | HTTP | requests + `rest_source.RESTClient` | ✅ |
| openaq | HTTP | requests | ✅ |
| openfda | HTTP | requests | ✅ |
+| openrouter | HTTP | requests | ✅ |
| openweather | HTTP | requests | ✅ |
| ortto | HTTP | requests | ✅ |
| oura | HTTP | requests | ✅ |
@@ -692,7 +693,6 @@ doesn't conflict with concurrent PRs.
- onesignal
- open_data_dc
- openai
-- openrouter
- opsgenie
- opuswatch
- oracle
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.py
index ee217727743e..ea113d92df07 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
@@ -2612,7 +2612,7 @@ class OpenFDASourceConfig(config.Config):
@config.config
class OpenRouterSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/canonical_descriptions.py
new file mode 100644
index 000000000000..746c6c58b721
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/canonical_descriptions.py
@@ -0,0 +1,130 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Curated from the OpenRouter OpenAPI spec (https://openrouter.ai/openapi.json). Applied directly as
+# authoritative table/column descriptions; any field not covered here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "models": {
+ "description": "Catalog of every model available through the OpenRouter gateway, including pricing, context length, architecture, and supported parameters.",
+ "docs_url": "https://openrouter.ai/docs/api-reference/list-available-models",
+ "columns": {
+ "id": "Unique identifier (slug) for the model, e.g. 'openai/gpt-4.1'.",
+ "canonical_slug": "Canonical slug for the model.",
+ "hugging_face_id": "Hugging Face model identifier, if applicable.",
+ "name": "Display name of the model.",
+ "created": "Unix timestamp of when the model was created.",
+ "description": "Description of the model.",
+ "context_length": "Maximum context length in tokens.",
+ "architecture": "Model architecture information (modality, input/output modalities, tokenizer).",
+ "pricing": "Pricing information for the model (per-token prompt/completion costs and more).",
+ "top_provider": "Information about the top provider serving this model.",
+ "per_request_limits": "Per-request token limits.",
+ "supported_parameters": "List of parameters the model supports.",
+ "default_parameters": "Default parameters for this model.",
+ "supported_voices": "List of supported voice identifiers for TTS models. Null for non-TTS models.",
+ "knowledge_cutoff": "The date up to which the model was trained on data (YYYY-MM-DD), or null if unknown.",
+ "expiration_date": "The date after which the model may be removed (YYYY-MM-DD), or null if no expiration.",
+ "benchmarks": "Third-party benchmark rankings for this model. Omitted when no benchmark data is available.",
+ "reasoning": "Reasoning effort configuration. Omitted for non-reasoning and dynamic router models.",
+ "links": "Related API endpoints and resources for this model.",
+ },
+ },
+ "providers": {
+ "description": "Catalog of inference providers that serve models through OpenRouter.",
+ "docs_url": "https://openrouter.ai/docs/api-reference/list-available-providers",
+ "columns": {
+ "slug": "URL-friendly identifier for the provider.",
+ "name": "Display name of the provider.",
+ "headquarters": "ISO 3166-1 Alpha-2 country code of the provider headquarters.",
+ "datacenters": "ISO 3166-1 Alpha-2 country codes of the provider datacenter locations.",
+ "privacy_policy_url": "URL to the provider's privacy policy.",
+ "terms_of_service_url": "URL to the provider's terms of service.",
+ "status_page_url": "URL to the provider's status page.",
+ },
+ },
+ "activity": {
+ "description": "Daily usage rollups grouped by provider endpoint for the last 30 completed UTC days: requests, tokens, and spend per model and provider.",
+ "docs_url": "https://openrouter.ai/docs/api-reference/analytics",
+ "columns": {
+ "date": "Date of the activity (YYYY-MM-DD format).",
+ "model": "Model slug, e.g. 'openai/gpt-4.1'.",
+ "model_permaslug": "Model permaslug, e.g. 'openai/gpt-4.1-2025-04-14'.",
+ "endpoint_id": "Unique identifier for the endpoint.",
+ "provider_name": "Name of the provider serving this endpoint.",
+ "usage": "Total cost in USD (OpenRouter credits spent).",
+ "byok_usage_inference": "BYOK inference cost in USD (external credits spent).",
+ "requests": "Number of requests made.",
+ "prompt_tokens": "Total prompt tokens used.",
+ "completion_tokens": "Total completion tokens generated.",
+ "reasoning_tokens": "Total reasoning tokens used.",
+ },
+ },
+ "api_keys": {
+ "description": "API keys belonging to the account or organization, with per-key usage and spending limits.",
+ "docs_url": "https://openrouter.ai/docs/api-reference/api-keys",
+ "columns": {
+ "hash": "Unique hash identifier for the API key.",
+ "name": "Name of the API key.",
+ "label": "Human-readable label for the API key.",
+ "disabled": "Whether the API key is disabled.",
+ "limit": "Spending limit for the API key in USD.",
+ "limit_remaining": "Remaining spending limit in USD.",
+ "limit_reset": "Type of limit reset for the API key.",
+ "usage": "Total OpenRouter credit usage (in USD) for the API key.",
+ "usage_daily": "OpenRouter credit usage (in USD) for the current UTC day.",
+ "usage_weekly": "OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday).",
+ "usage_monthly": "OpenRouter credit usage (in USD) for the current UTC month.",
+ "byok_usage": "Total external BYOK usage (in USD) for the API key.",
+ "byok_usage_daily": "External BYOK usage (in USD) for the current UTC day.",
+ "byok_usage_weekly": "External BYOK usage (in USD) for the current UTC week (Monday-Sunday).",
+ "byok_usage_monthly": "External BYOK usage (in USD) for the current UTC month.",
+ "include_byok_in_limit": "Whether external BYOK usage counts against the credit limit.",
+ "creator_user_id": "User ID of the key creator.",
+ "workspace_id": "The workspace ID this API key belongs to.",
+ "expires_at": "ISO 8601 UTC timestamp when the API key expires, or null if no expiration.",
+ "created_at": "ISO 8601 timestamp of when the API key was created.",
+ "updated_at": "ISO 8601 timestamp of when the API key was last updated.",
+ },
+ },
+ "credits": {
+ "description": "Current credit balance for the account: total credits purchased and total credits used.",
+ "docs_url": "https://openrouter.ai/docs/api-reference/get-credits",
+ "columns": {
+ "total_credits": "Total credits purchased.",
+ "total_usage": "Total credits used.",
+ },
+ },
+ "organization_members": {
+ "description": "Members of the OpenRouter organization and their roles.",
+ "docs_url": "https://openrouter.ai/docs/api-reference/organization",
+ "columns": {
+ "id": "User ID of the organization member.",
+ "email": "Email address of the member.",
+ "first_name": "First name of the member.",
+ "last_name": "Last name of the member.",
+ "role": "Role of the member in the organization.",
+ },
+ },
+ "workspaces": {
+ "description": "Workspaces within the organization, including their default models and observability settings.",
+ "docs_url": "https://openrouter.ai/docs/api-reference/workspaces",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "slug": "URL-friendly slug for the workspace.",
+ "name": "Name of the workspace.",
+ "description": "Description of the workspace.",
+ "created_by": "User ID of the workspace creator.",
+ "default_text_model": "Default text model for this workspace.",
+ "default_image_model": "Default image model for this workspace.",
+ "default_provider_sort": "Default provider sort preference (price, throughput, latency, exacto).",
+ "io_logging_api_key_ids": "Optional array of API key IDs to filter I/O logging. Null means all keys are logged.",
+ "io_logging_sampling_rate": "Sampling rate for I/O logging (0.0001-1). 1 means 100% of requests are logged.",
+ "is_observability_io_logging_enabled": "Whether private logging is enabled for this workspace.",
+ "is_observability_broadcast_enabled": "Whether broadcast is enabled for this workspace.",
+ "is_data_discount_logging_enabled": "Whether data discount logging is enabled for this workspace.",
+ "created_at": "ISO 8601 timestamp of when the workspace was created.",
+ "updated_at": "ISO 8601 timestamp of when the workspace was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/openrouter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/openrouter.py
new file mode 100644
index 000000000000..a3b8435e46bf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/openrouter.py
@@ -0,0 +1,274 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.settings import (
+ ACTIVITY_RETENTION_DAYS,
+ OPENROUTER_ENDPOINTS,
+ OpenRouterEndpointConfig,
+)
+
+OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
+REQUEST_TIMEOUT = 60
+MAX_OFFSET_PAGES = 10_000
+
+
+class OpenRouterRetryableError(Exception):
+ pass
+
+
+class OpenRouterResumeConfig:
+ # Offset already fetched for offset-paginated endpoints (api_keys/organization_members/workspaces).
+ offset: int | None = None
+ # Last fully-synced UTC day (YYYY-MM-DD) for the /activity day-by-day pull.
+ date: str | None = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _build_url(path: str, params: Optional[dict[str, Any]] = None) -> str:
+ url = f"{OPENROUTER_BASE_URL}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ return url
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ OpenRouterRetryableError,
+ 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, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise OpenRouterRetryableError(f"OpenRouter API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Don't log the raw response body: several endpoints (api_keys/organization_members/workspaces)
+ # return sensitive management data and upstream error bodies can echo request context.
+ logger.error(f"OpenRouter API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_key_info(api_key: str) -> dict[str, Any] | None:
+ """Return the current key's metadata from GET /key, or None if the key is invalid.
+
+ The response carries `is_management_key`, which tells us whether the management endpoints
+ (activity/api_keys/credits/organization_members/workspaces) will be reachable — a regular
+ inference key can only read the public models/providers catalogs.
+ """
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ _build_url("/key"), headers=_headers(api_key), timeout=10
+ )
+ if response.status_code == 200:
+ data = response.json().get("data")
+ return data if isinstance(data, dict) else {}
+ return None
+ except Exception:
+ return None
+
+
+def validate_credentials(api_key: str) -> bool:
+ return get_key_info(api_key) is not None
+
+
+def _to_date(value: Any) -> date | None:
+ """Coerce an incremental cursor / resume bookmark into a UTC date."""
+ if isinstance(value, datetime):
+ return value.astimezone(UTC).date() if value.tzinfo else value.date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, str):
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()
+ except ValueError:
+ try:
+ return date.fromisoformat(value[:10])
+ except ValueError:
+ return None
+ return None
+
+
+def _activity_days(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> Iterator[date]:
+ """Yield each completed UTC day to pull from /activity, oldest first.
+
+ OpenRouter only retains the last 30 completed UTC days, so the window is clamped to that regardless
+ of the watermark. On an incremental sync we re-fetch the watermark day itself (it may have been
+ partial when first synced); merge dedupes the re-pulled rows on the primary key.
+ """
+ yesterday = datetime.now(UTC).date() - timedelta(days=1)
+ start = yesterday - timedelta(days=ACTIVITY_RETENTION_DAYS - 1)
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ watermark = _to_date(db_incremental_field_last_value)
+ if watermark is not None and watermark > start:
+ start = watermark
+
+ day = start
+ while day <= yesterday:
+ yield day
+ day += timedelta(days=1)
+
+
+def _get_activity_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenRouterResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ resume_from = _to_date(resume.date) if resume is not None and resume.date else None
+
+ for day in _activity_days(should_use_incremental_field, db_incremental_field_last_value):
+ # Skip days a crashed prior attempt already completed. The window is regenerated from the
+ # watermark on resume, so this is what advances us past the point of the crash.
+ if resume_from is not None and day <= resume_from:
+ continue
+
+ data = _fetch(session, _build_url("/activity", {"date": day.isoformat()}), headers, logger)
+ rows = data.get("data") or []
+ if rows:
+ yield rows
+
+ # Save AFTER yielding so a crash re-yields the last day rather than skipping it.
+ resumable_source_manager.save_state(OpenRouterResumeConfig(date=day.isoformat()))
+
+
+def _get_offset_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenRouterResumeConfig],
+ config: OpenRouterEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume is not None and resume.offset else 0
+
+ # Hard cap as a runaway guard in case an endpoint ignores `offset` and re-serves the same page.
+ for _ in range(MAX_OFFSET_PAGES):
+ params: dict[str, Any] = {"offset": offset}
+ if config.pagination == "offset_limit":
+ params["limit"] = config.page_size
+
+ data = _fetch(session, _build_url(config.path, params), headers, logger)
+ rows = data.get("data") or []
+ if not rows:
+ break
+
+ yield rows
+
+ # When we set the page size ourselves (`limit`), a short page is the last page. For the
+ # offset-only endpoints we don't know the server's page size, so we keep going until an
+ # empty page instead of guessing it.
+ if config.pagination == "offset_limit" and len(rows) < config.page_size:
+ break
+
+ offset += len(rows)
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary key).
+ resumable_source_manager.save_state(OpenRouterResumeConfig(offset=offset))
+ else:
+ logger.warning(f"OpenRouter: hit the {MAX_OFFSET_PAGES}-page cap for {config.name}; stopping pagination")
+
+
+def _get_single_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: OpenRouterEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ data = _fetch(session, _build_url(config.path), headers, logger)
+
+ if config.is_singleton:
+ obj = data.get("data")
+ if isinstance(obj, dict) and obj:
+ yield [obj]
+ return
+
+ rows = data.get("data") or []
+ if rows:
+ yield rows
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenRouterResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = OPENROUTER_ENDPOINTS[endpoint]
+ headers = _headers(api_key)
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if config.daily_activity:
+ yield from _get_activity_rows(
+ session,
+ headers,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.pagination is not None:
+ yield from _get_offset_rows(session, headers, logger, resumable_source_manager, config)
+ else:
+ yield from _get_single_rows(session, headers, logger, config)
+
+
+def openrouter_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenRouterResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = OPENROUTER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # /activity yields days oldest-first and offset pages advance forward, so the watermark
+ # checkpoints safely after each batch.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/settings.py
new file mode 100644
index 000000000000..524cde64aadc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/settings.py
@@ -0,0 +1,106 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# The /activity rollups only cover the last 30 completed UTC days; older data isn't retrievable
+# through this endpoint, so both the first sync and every incremental sync are bounded to this window.
+ACTIVITY_RETENTION_DAYS = 30
+
+PaginationMode = Literal["offset", "offset_limit"]
+
+
+@dataclass
+class OpenRouterEndpointConfig:
+ name: str
+ path: str
+ # Management endpoints (activity/api_keys/credits/organization_members/workspaces) require an
+ # OpenRouter management key; the models/providers catalogs are public and read with any valid key.
+ requires_management_key: bool
+ # Table-wide unique key. None for the /credits singleton (a single balance snapshot, full-refresh
+ # replace, so there's nothing to merge on).
+ primary_keys: Optional[list[str]] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime field to partition by (never a mutable field like updated_at).
+ partition_key: Optional[str] = None
+ # Offset-based pagination style, or None for a single unpaginated request.
+ # "offset" -> only an `offset` query param (e.g. /keys)
+ # "offset_limit" -> `offset` + `limit` query params (e.g. /organization/members, /workspaces)
+ pagination: Optional[PaginationMode] = None
+ page_size: int = 100
+ # `data` is a single object rather than a list of rows (e.g. /credits).
+ is_singleton: bool = False
+ # Day-by-day pull driven by the ?date= filter (only /activity). See openrouter.py.
+ daily_activity: bool = False
+ should_sync_default: bool = True
+
+
+# /activity is the only endpoint with a genuine server-side time filter (?date=<single UTC day>), so
+# it's the only incremental table. Everything else is a small full-refresh table.
+_ACTIVITY_DATE_FIELD: IncrementalField = {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+}
+
+
+OPENROUTER_ENDPOINTS: dict[str, OpenRouterEndpointConfig] = {
+ "models": OpenRouterEndpointConfig(
+ name="models",
+ path="/models",
+ requires_management_key=False,
+ primary_keys=["id"],
+ ),
+ "providers": OpenRouterEndpointConfig(
+ name="providers",
+ path="/providers",
+ requires_management_key=False,
+ primary_keys=["slug"],
+ ),
+ "activity": OpenRouterEndpointConfig(
+ name="activity",
+ path="/activity",
+ requires_management_key=True,
+ # A row is one provider endpoint's usage for one UTC day; endpoint_id alone should be unique
+ # per day, but the model/provider are included defensively so the key can't collide.
+ primary_keys=["date", "endpoint_id", "model_permaslug", "provider_name"],
+ partition_key="date",
+ incremental_fields=[_ACTIVITY_DATE_FIELD],
+ daily_activity=True,
+ ),
+ "api_keys": OpenRouterEndpointConfig(
+ name="api_keys",
+ path="/keys",
+ requires_management_key=True,
+ primary_keys=["hash"],
+ pagination="offset",
+ ),
+ "credits": OpenRouterEndpointConfig(
+ name="credits",
+ path="/credits",
+ requires_management_key=True,
+ primary_keys=None,
+ is_singleton=True,
+ ),
+ "organization_members": OpenRouterEndpointConfig(
+ name="organization_members",
+ path="/organization/members",
+ requires_management_key=True,
+ primary_keys=["id"],
+ pagination="offset_limit",
+ ),
+ "workspaces": OpenRouterEndpointConfig(
+ name="workspaces",
+ path="/workspaces",
+ requires_management_key=True,
+ primary_keys=["id"],
+ pagination="offset_limit",
+ ),
+}
+
+ENDPOINTS = tuple(OPENROUTER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in OPENROUTER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py
index 1f65645387a8..2c6c795b9586 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/source.py
@@ -1,19 +1,48 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.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.generated_configs import OpenRouterSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.openrouter import (
+ OpenRouterResumeConfig,
+ get_key_info,
+ openrouter_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ OPENROUTER_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_MANAGEMENT_KEY_REQUIRED = (
+ "Requires an OpenRouter management API key. This key is a regular inference key, which can only "
+ "read the models and providers catalogs."
+)
+
@SourceRegistry.register
-class OpenRouterSource(SimpleSource[OpenRouterSourceConfig]):
+class OpenRouterSource(ResumableSource[OpenRouterSourceConfig, OpenRouterResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OPENROUTER
@@ -24,8 +53,129 @@ class OpenRouterSource(SimpleSource[OpenRouterSourceConfig]):
name=SchemaExternalDataSourceType.OPEN_ROUTER,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="OpenRouter",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your OpenRouter API key to pull your OpenRouter usage and account data into the PostHog Data warehouse.
+
+Use a **management API key** (create one under [Settings -> Management Keys](https://openrouter.ai/settings/keys)) so the activity, API keys, credits, organization members, and workspaces tables can sync. A regular inference key can only read the models and providers catalogs.""",
iconPath="/static/services/openrouter.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/openrouter",
keywords=["llm", "ai gateway", "usage", "inference"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sk-or-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad or revoked key surfaces as an HTTPError from `raise_for_status()`. Match the stable
+ # status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://openrouter.ai": "Your OpenRouter API key is invalid or has been revoked. Create a new key in your OpenRouter dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://openrouter.ai": "Your OpenRouter API key is missing the management scope needed to sync this data. Use a management API key (Settings -> Management Keys), then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: OpenRouterSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "activity":
+ return "Daily usage rollups; only the last 30 completed UTC days are available"
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ # /activity re-fetches the (possibly partial) watermark day each run, so it relies on
+ # merge to dedupe — append would materialize duplicates. Every other table is small
+ # and full-refresh only.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=OPENROUTER_ENDPOINTS[endpoint].should_sync_default,
+ description=_description(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) 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: OpenRouterSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ info = get_key_info(config.api_key)
+ if info is None:
+ return False, "Invalid OpenRouter API key. Create a key in your OpenRouter dashboard and try again."
+
+ # At source-create (no schema_name) any genuine key is accepted — the catalog tables sync with
+ # an inference key, and get_endpoint_permissions reports which tables need a management key.
+ # When validating a specific management table, require the management scope.
+ if schema_name is not None:
+ endpoint = OPENROUTER_ENDPOINTS.get(schema_name)
+ if endpoint is not None and endpoint.requires_management_key and not info.get("is_management_key"):
+ return False, f"The '{schema_name}' table requires an OpenRouter management API key."
+
+ return True, None
+
+ def get_endpoint_permissions(
+ self, config: OpenRouterSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ info = get_key_info(config.api_key)
+ # A None here is a transient /key failure, not a denial (the key was already validated at
+ # create). Only a genuine 200 that reports a non-management key marks the management tables.
+ if info is None:
+ return dict.fromkeys(endpoints)
+
+ is_management_key = bool(info.get("is_management_key"))
+
+ result: dict[str, str | None] = {}
+ for name in endpoints:
+ endpoint = OPENROUTER_ENDPOINTS.get(name)
+ if endpoint is not None and endpoint.requires_management_key and not is_management_key:
+ result[name] = _MANAGEMENT_KEY_REQUIRED
+ else:
+ result[name] = None
+ return result
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenRouterResumeConfig]:
+ return ResumableSourceManager[OpenRouterResumeConfig](inputs, OpenRouterResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OpenRouterSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OpenRouterResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return openrouter_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ 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/openrouter/tests/test_openrouter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter.py
new file mode 100644
index 000000000000..30631c744a00
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter.py
@@ -0,0 +1,283 @@
+from datetime import UTC, date, datetime, timedelta
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter import openrouter
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.openrouter import (
+ OpenRouterResumeConfig,
+ _activity_days,
+ _to_date,
+ get_rows,
+ openrouter_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.settings import (
+ ACTIVITY_RETENTION_DAYS,
+ OPENROUTER_ENDPOINTS,
+)
+
+
+def _response(status_code: int, body: dict | None = None, text: str = "") -> mock.Mock:
+ response = mock.Mock(spec=requests.Response)
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 300
+ response.text = text
+ response.json.return_value = body or {}
+ response.request = None
+ if not response.ok:
+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(
+ f"{status_code} Client Error for url: https://openrouter.ai", response=response
+ )
+ return response
+
+
+def _no_resume() -> mock.Mock:
+ manager = mock.Mock()
+ manager.can_resume.return_value = False
+ manager.load_state.return_value = None
+ return manager
+
+
+class TestFetch:
+ @pytest.fixture(autouse=True)
+ def _instant_retry(self):
+ # Zero the tenacity backoff so retry tests don't actually sleep.
+ with mock.patch.object(openrouter._fetch.retry, "wait", return_value=0): # type: ignore[attr-defined]
+ yield
+
+ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])
+ def test_retries_then_succeeds_on_transient_status(self, status_code):
+ session = mock.Mock()
+ session.get.side_effect = [_response(status_code), _response(200, {"data": []})]
+
+ result = openrouter._fetch(session, "https://openrouter.ai/api/v1/models", {}, mock.Mock())
+
+ assert result == {"data": []}
+ assert session.get.call_count == 2
+
+ @pytest.mark.parametrize("status_code", [400, 401, 403, 404])
+ def test_client_errors_raise(self, status_code):
+ session = mock.Mock()
+ session.get.return_value = _response(status_code, text="nope")
+
+ with pytest.raises(requests.exceptions.HTTPError):
+ openrouter._fetch(session, "https://openrouter.ai/api/v1/keys", {}, mock.Mock())
+
+
+class TestGetKeyInfo:
+ def test_returns_data_on_200(self):
+ session = mock.Mock()
+ session.get.return_value = _response(200, {"data": {"is_management_key": True}})
+ with mock.patch.object(openrouter, "make_tracked_session", return_value=session):
+ assert openrouter.get_key_info("sk-or-x") == {"is_management_key": True}
+
+ @pytest.mark.parametrize("status_code", [401, 403, 500])
+ def test_returns_none_on_non_200(self, status_code):
+ session = mock.Mock()
+ session.get.return_value = _response(status_code)
+ with mock.patch.object(openrouter, "make_tracked_session", return_value=session):
+ assert openrouter.get_key_info("sk-or-x") is None
+
+ def test_validate_credentials_wraps_get_key_info(self):
+ with mock.patch.object(openrouter, "get_key_info", return_value={"is_management_key": False}):
+ assert openrouter.validate_credentials("sk-or-x") is True
+ with mock.patch.object(openrouter, "get_key_info", return_value=None):
+ assert openrouter.validate_credentials("sk-or-x") is False
+
+
+class TestToDate:
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ ("2026-06-15", date(2026, 6, 15)),
+ ("2026-06-15T12:00:00Z", date(2026, 6, 15)),
+ (date(2026, 6, 15), date(2026, 6, 15)),
+ (datetime(2026, 6, 15, 8, tzinfo=UTC), date(2026, 6, 15)),
+ ("not-a-date", None),
+ (None, None),
+ ],
+ )
+ def test_coercion(self, value, expected):
+ assert _to_date(value) == expected
+
+
+class TestActivityDays:
+ def test_full_window_when_no_watermark(self):
+ yesterday = datetime.now(UTC).date() - timedelta(days=1)
+ days = list(_activity_days(should_use_incremental_field=False, db_incremental_field_last_value=None))
+ assert len(days) == ACTIVITY_RETENTION_DAYS
+ assert days[-1] == yesterday
+ assert days[0] == yesterday - timedelta(days=ACTIVITY_RETENTION_DAYS - 1)
+ assert days == sorted(days) # ascending
+
+ def test_watermark_inside_window_refetches_from_watermark(self):
+ yesterday = datetime.now(UTC).date() - timedelta(days=1)
+ watermark = yesterday - timedelta(days=3)
+ days = list(_activity_days(True, watermark))
+ # The watermark day itself is re-fetched (it may have been partial); merge dedupes.
+ assert days[0] == watermark
+ assert days[-1] == yesterday
+
+ def test_stale_watermark_clamped_to_retention_window(self):
+ watermark = datetime.now(UTC).date() - timedelta(days=90)
+ days = list(_activity_days(True, watermark))
+ assert len(days) == ACTIVITY_RETENTION_DAYS
+
+ def test_future_watermark_yields_nothing(self):
+ watermark = datetime.now(UTC).date() + timedelta(days=5)
+ assert list(_activity_days(True, watermark)) == []
+
+
+class TestActivityRows:
+ def test_pulls_each_day_and_saves_state_after_yield(self):
+ manager = _no_resume()
+ calls: list[str] = []
+
+ def fake_fetch(session, url, headers, logger):
+ calls.append(url)
+ return {"data": [{"date": "2026-06-01", "endpoint_id": "e1"}]}
+
+ with mock.patch.object(openrouter, "_fetch", side_effect=fake_fetch):
+ batches = list(
+ get_rows(
+ "sk-or-x",
+ "activity",
+ mock.Mock(),
+ manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ )
+
+ assert len(batches) == ACTIVITY_RETENTION_DAYS
+ assert all("date=" in url for url in calls)
+ # State saved once per day, after each yield.
+ assert manager.save_state.call_count == ACTIVITY_RETENTION_DAYS
+ assert isinstance(manager.save_state.call_args.args[0], OpenRouterResumeConfig)
+
+ def test_resume_skips_already_completed_days(self):
+ yesterday = datetime.now(UTC).date() - timedelta(days=1)
+ already_done = yesterday - timedelta(days=1)
+
+ manager = mock.Mock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = OpenRouterResumeConfig(date=already_done.isoformat())
+
+ fetched_dates: list[str] = []
+
+ def fake_fetch(session, url, headers, logger):
+ fetched_dates.append(url.split("date=")[1])
+ return {"data": []}
+
+ with mock.patch.object(openrouter, "_fetch", side_effect=fake_fetch):
+ list(
+ get_rows(
+ "sk-or-x",
+ "activity",
+ mock.Mock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=(yesterday - timedelta(days=10)).isoformat(),
+ )
+ )
+
+ # Only the day after the completed bookmark (yesterday) is fetched.
+ assert fetched_dates == [yesterday.isoformat()]
+
+
+class TestOffsetPagination:
+ def test_offset_limit_stops_on_short_page(self):
+ # organization_members sends `limit`, so a page shorter than the limit is the last page.
+ manager = _no_resume()
+ page1 = {"data": [{"id": f"m{i}"} for i in range(100)]}
+ page2 = {"data": [{"id": "m100"}]}
+
+ def fake_fetch(session, url, headers, logger):
+ return page1 if "offset=0" in url else page2
+
+ with mock.patch.object(openrouter, "_fetch", side_effect=fake_fetch):
+ batches = list(get_rows("sk-or-x", "organization_members", mock.Mock(), manager))
+
+ assert [len(b) for b in batches] == [100, 1]
+ # State saved after the first full page, not after the short page.
+ assert manager.save_state.call_count == 1
+
+ def test_offset_only_stops_on_empty_page(self):
+ # api_keys doesn't send `limit` (unknown server page size), so it walks until an empty page.
+ manager = _no_resume()
+ seen: list[str] = []
+
+ def fake_fetch(session, url, headers, logger):
+ seen.append(url)
+ return {"data": [{"hash": f"k{i}"} for i in range(100)]} if "offset=0" in url else {"data": []}
+
+ with mock.patch.object(openrouter, "_fetch", side_effect=fake_fetch):
+ batches = list(get_rows("sk-or-x", "api_keys", mock.Mock(), manager))
+
+ assert [len(b) for b in batches] == [100]
+ assert any("offset=100" in u for u in seen)
+ assert manager.save_state.call_count == 1
+
+ def test_resume_from_saved_offset(self):
+ manager = mock.Mock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = OpenRouterResumeConfig(offset=100)
+ seen: list[str] = []
+
+ def fake_fetch(session, url, headers, logger):
+ seen.append(url)
+ return {"data": [{"hash": "k"}]} if "offset=100" in url else {"data": []}
+
+ with mock.patch.object(openrouter, "_fetch", side_effect=fake_fetch):
+ list(get_rows("sk-or-x", "api_keys", mock.Mock(), manager))
+
+ assert "offset=100" in seen[0]
+
+ def test_offset_limit_endpoints_send_limit(self):
+ manager = _no_resume()
+ urls: list[str] = []
+
+ def fake_fetch(session, url, headers, logger):
+ urls.append(url)
+ return {"data": []}
+
+ with mock.patch.object(openrouter, "_fetch", side_effect=fake_fetch):
+ list(get_rows("sk-or-x", "organization_members", mock.Mock(), manager))
+
+ assert "limit=" in urls[0]
+
+
+class TestSingleAndSingleton:
+ def test_models_yields_list(self):
+ manager = _no_resume()
+ with mock.patch.object(openrouter, "_fetch", return_value={"data": [{"id": "a"}, {"id": "b"}]}):
+ batches = list(get_rows("sk-or-x", "models", mock.Mock(), manager))
+ assert batches == [[{"id": "a"}, {"id": "b"}]]
+
+ def test_credits_singleton_wrapped_in_list(self):
+ manager = _no_resume()
+ with mock.patch.object(openrouter, "_fetch", return_value={"data": {"total_credits": 10, "total_usage": 3}}):
+ batches = list(get_rows("sk-or-x", "credits", mock.Mock(), manager))
+ assert batches == [[{"total_credits": 10, "total_usage": 3}]]
+
+
+class TestSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint,expected_keys", [(name, cfg.primary_keys) for name, cfg in OPENROUTER_ENDPOINTS.items()]
+ )
+ def test_primary_keys_match_settings(self, endpoint, expected_keys):
+ response = openrouter_source("sk-or-x", endpoint, mock.Mock(), _no_resume())
+ assert response.primary_keys == expected_keys
+ assert response.sort_mode == "asc"
+
+ def test_activity_partitions_on_date(self):
+ response = openrouter_source("sk-or-x", "activity", mock.Mock(), _no_resume())
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["date"]
+
+ def test_catalog_tables_not_partitioned(self):
+ response = openrouter_source("sk-or-x", "models", mock.Mock(), _no_resume())
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter_source.py
new file mode 100644
index 000000000000..b089b4bfae9b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openrouter/tests/test_openrouter_source.py
@@ -0,0 +1,156 @@
+from typing import Optional
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OpenRouterSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.openrouter import (
+ OpenRouterResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openrouter.source import OpenRouterSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MANAGEMENT_ENDPOINTS = ["activity", "api_keys", "credits", "organization_members", "workspaces"]
+CATALOG_ENDPOINTS = ["models", "providers"]
+
+
+def _patch_key_info(info: Optional[dict]):
+ return mock.patch.object(source_module, "get_key_info", return_value=info)
+
+
+class TestOpenRouterSource:
+ def setup_method(self):
+ self.source = OpenRouterSource()
+ self.team_id = 123
+ self.config = OpenRouterSourceConfig(api_key="sk-or-test")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.OPENROUTER
+
+ def test_source_config_fields(self):
+ config = self.source.get_source_config
+ assert config.label == "OpenRouter"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is not hidden.
+ assert config.unreleasedSource is None or config.unreleasedSource is False
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/openrouter"
+
+ assert len(config.fields) == 1
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+
+ def test_lists_tables_without_credentials(self):
+ # Static endpoint catalog with no I/O — required for the public-docs table list to render.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_only_activity_is_incremental(self):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert set(schemas) == set(MANAGEMENT_ENDPOINTS) | set(CATALOG_ENDPOINTS)
+ assert schemas["activity"].supports_incremental is True
+ assert [f["field"] for f in schemas["activity"].incremental_fields] == ["date"]
+ for name, schema in schemas.items():
+ if name != "activity":
+ assert schema.supports_incremental is False, name
+ # No table advertises append: activity relies on merge to dedupe re-fetched days.
+ assert schema.supports_append is False, name
+
+ def test_get_schemas_filters_by_name(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["models", "activity"])
+ assert {s.name for s in schemas} == {"models", "activity"}
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())
+
+ def test_validate_credentials_invalid_key(self):
+ with _patch_key_info(None):
+ ok, error = self.source.validate_credentials(self.config, self.team_id)
+ assert ok is False
+ assert error is not None
+
+ def test_validate_credentials_accepts_any_genuine_key_at_create(self):
+ # An inference (non-management) key must still connect: the catalog tables sync, and
+ # get_endpoint_permissions reports which tables need a management key.
+ with _patch_key_info({"is_management_key": False}):
+ ok, error = self.source.validate_credentials(self.config, self.team_id, schema_name=None)
+ assert ok is True
+ assert error is None
+
+ @pytest.mark.parametrize("schema_name", MANAGEMENT_ENDPOINTS)
+ def test_validate_credentials_rejects_non_management_key_for_management_table(self, schema_name):
+ with _patch_key_info({"is_management_key": False}):
+ ok, error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert ok is False
+ assert error is not None and "management" in error.lower()
+
+ @pytest.mark.parametrize("schema_name", CATALOG_ENDPOINTS)
+ def test_validate_credentials_allows_catalog_tables_for_any_key(self, schema_name):
+ with _patch_key_info({"is_management_key": False}):
+ ok, error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert ok is True
+ assert error is None
+
+ def test_endpoint_permissions_flag_management_tables_for_inference_key(self):
+ with _patch_key_info({"is_management_key": False}):
+ result = self.source.get_endpoint_permissions(
+ self.config, self.team_id, MANAGEMENT_ENDPOINTS + CATALOG_ENDPOINTS
+ )
+ for name in CATALOG_ENDPOINTS:
+ assert result[name] is None
+ for name in MANAGEMENT_ENDPOINTS:
+ assert result[name] is not None
+
+ def test_endpoint_permissions_all_reachable_with_management_key(self):
+ with _patch_key_info({"is_management_key": True}):
+ result = self.source.get_endpoint_permissions(
+ self.config, self.team_id, MANAGEMENT_ENDPOINTS + CATALOG_ENDPOINTS
+ )
+ assert all(v is None for v in result.values())
+
+ def test_resumable_manager_bound_to_resume_config(self):
+ inputs = mock.Mock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is OpenRouterResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self):
+ inputs = mock.Mock()
+ inputs.schema_name = "activity"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-06-01"
+ manager = mock.Mock()
+
+ with mock.patch.object(source_module, "openrouter_source") as mocked:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mocked.assert_called_once()
+ kwargs = mocked.call_args.kwargs
+ assert kwargs["api_key"] == "sk-or-test"
+ assert kwargs["endpoint"] == "activity"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-06-01"
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self):
+ inputs = mock.Mock()
+ inputs.schema_name = "models"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-06-01"
+
+ with mock.patch.object(source_module, "openrouter_source") as mocked:
+ self.source.source_for_pipeline(self.config, mock.Mock(), inputs)
+
+ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_documented_tables_rendered_for_public_docs(self):
+ tables = self.source.get_documented_tables()
+ by_name = {t["name"]: t for t in tables}
+ assert set(by_name) == set(MANAGEMENT_ENDPOINTS) | set(CATALOG_ENDPOINTS)
+ # Canonical descriptions flow through to the docs.
+ assert by_name["activity"]["description"]
+ assert "Incremental" in by_name["activity"]["sync_methods"]
+ assert "Full refresh" in by_name["models"]["sync_methods"]