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 nebius_ai import source (#69995)

Tom Owers77cc9f355ef5
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 9953857e86aa..582b299f9839 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -280,6 +280,7 @@ the row lists both.
| my_hours | HTTP | requests | ✅ |
| mysql | DB protocol | pymysql | ➖ |
| n8n | HTTP | requests | ✅ |
+| nebius_ai | HTTP | requests | ✅ |
| netlify | HTTP | requests | ✅ |
| new_york_times | HTTP | requests | ✅ |
| news_api | HTTP | requests | ✅ |
@@ -674,7 +675,6 @@ doesn't conflict with concurrent PRs.
- mono
- nasa
- navan
-- nebius_ai
- neon
- netsuite
- new_relic
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 0d1c303bdb72..24ecf376e27c 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
@@ -2444,7 +2444,7 @@ class NavanSourceConfig(config.Config):
@config.config
class NebiusAISourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/canonical_descriptions.py
new file mode 100644
index 000000000000..dde2f8e3315e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/canonical_descriptions.py
@@ -0,0 +1,65 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from Nebius AI Studio (Token Factory) docs, which follow the OpenAI-compatible
+# object schemas. Keyed by the endpoint/schema name returned by `get_schemas`.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "models": {
+ "description": "Models available to your Nebius AI Studio account for inference and fine-tuning.",
+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference",
+ "columns": {
+ "id": "Model identifier used when requesting inference (e.g. meta-llama/Llama-3.3-70B-Instruct).",
+ "object": "Object type, always 'model'.",
+ "created": "Unix timestamp (seconds) for when the model was created.",
+ "owned_by": "Organization or provider that owns the model.",
+ },
+ },
+ "files": {
+ "description": "Files uploaded to Nebius AI Studio, such as batch inputs and fine-tuning datasets.",
+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference",
+ "columns": {
+ "id": "Unique identifier for the file.",
+ "object": "Object type, always 'file'.",
+ "bytes": "Size of the file in bytes.",
+ "created_at": "Unix timestamp (seconds) for when the file was created.",
+ "filename": "Name of the uploaded file.",
+ "purpose": "Intended use of the file (e.g. 'batch', 'fine-tune').",
+ "status": "Processing status of the file.",
+ },
+ },
+ "batches": {
+ "description": "Batch inference jobs that process a file of requests asynchronously.",
+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference",
+ "columns": {
+ "id": "Unique identifier for the batch.",
+ "object": "Object type, always 'batch'.",
+ "endpoint": "API endpoint the batch runs against (e.g. /v1/chat/completions).",
+ "input_file_id": "ID of the uploaded file containing the batch's requests.",
+ "completion_window": "Time window within which the batch should be processed.",
+ "status": "Current status of the batch (e.g. validating, in_progress, completed, failed).",
+ "output_file_id": "ID of the file containing successful request outputs.",
+ "error_file_id": "ID of the file containing failed request errors.",
+ "created_at": "Unix timestamp (seconds) for when the batch was created.",
+ "completed_at": "Unix timestamp (seconds) for when the batch finished.",
+ "request_counts": "Counts of total, completed, and failed requests in the batch.",
+ },
+ },
+ "fine_tuning_jobs": {
+ "description": "Fine-tuning jobs that train a custom model from a base model and a training file.",
+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference",
+ "columns": {
+ "id": "Unique identifier for the fine-tuning job.",
+ "object": "Object type, always 'fine_tuning.job'.",
+ "model": "Base model being fine-tuned.",
+ "created_at": "Unix timestamp (seconds) for when the job was created.",
+ "finished_at": "Unix timestamp (seconds) for when the job finished, if it has.",
+ "fine_tuned_model": "Identifier of the resulting fine-tuned model, once available.",
+ "status": "Current status of the job (e.g. queued, running, succeeded, failed, cancelled).",
+ "training_file": "ID of the file used for training.",
+ "validation_file": "ID of the file used for validation, if provided.",
+ "hyperparameters": "Hyperparameters used for the fine-tuning run.",
+ "trained_tokens": "Total number of billable tokens processed by the job.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/nebius_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/nebius_ai.py
new file mode 100644
index 000000000000..e8b759f72375
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/nebius_ai.py
@@ -0,0 +1,178 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.settings import NEBIUS_AI_ENDPOINTS
+
+# Token Factory rebrand of the former api.studio.nebius.ai host. OpenAI-compatible surface.
+NEBIUS_AI_BASE_URL = "https://api.tokenfactory.nebius.com/v1"
+
+# OpenAI-style `limit`. Nebius accepts up to 100 on the paginated list endpoints.
+PAGE_SIZE = 100
+
+
+class NebiusAIRetryableError(Exception):
+ pass
+
+
+class NebiusAIResumeConfig:
+ # OpenAI-style cursor: the id of the last object already yielded, sent as `after` to fetch the
+ # next page. None starts the list from the beginning.
+ after: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ url = f"{NEBIUS_AI_BASE_URL}{path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ # /models is the cheapest authenticated probe: every valid key can read it and it needs no params.
+ # `redact_values` keeps the key out of captured request samples; redirects are pinned off so the
+ # bearer token is never replayed to a host the probe did not validate against.
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+ try:
+ response = session.get(f"{NEBIUS_AI_BASE_URL}/models", headers=_get_headers(api_key), timeout=10)
+ except requests.RequestException as exc:
+ # A timeout or connection blip is not a credential problem — never report it as an invalid key.
+ return False, f"Could not reach Nebius AI: {exc}"
+
+ if response.ok:
+ return True, None
+
+ if response.status_code == 401:
+ return (
+ False,
+ "Your Nebius AI API key is invalid or has expired. Create a new key in the Nebius AI Studio console, then reconnect.",
+ )
+
+ if response.status_code == 403:
+ return (
+ False,
+ "Your Nebius AI API key does not have the permissions needed to sync this data. Grant read access to the key, then reconnect.",
+ )
+
+ # 429/5xx and other unexpected statuses are transient; don't mislabel the key as invalid.
+ return False, f"Nebius AI API returned status {response.status_code}, try reconnecting shortly."
+
+
+@retry(
+ # ChunkedEncodingError is a mid-stream connection break, transient like ConnectionError/ReadTimeout.
+ retry=retry_if_exception_type(
+ (
+ NebiusAIRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # Nebius enforces per-plan rate limits with 429s; retry those and transient 5xx with backoff.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise NebiusAIRetryableError(f"Nebius AI API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Nebius AI API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NebiusAIResumeConfig],
+) -> Iterator[Any]:
+ config = NEBIUS_AI_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive. `redact_values`
+ # masks the key in captured samples; `allow_redirects=False` stops the bearer token being replayed
+ # to an attacker-controlled host on a 30x.
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+
+ if not config.paginated:
+ data = _fetch_page(session, _build_url(config.path, {}), headers, logger)
+ items = data.get("data", [])
+ if items:
+ yield items
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ after = resume.after if resume else None
+
+ while True:
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if after:
+ params["after"] = after
+
+ data = _fetch_page(session, _build_url(config.path, params), headers, logger)
+ items = data.get("data", [])
+ if not items:
+ break
+
+ yield items
+
+ # Prefer the server-provided cursor; fall back to the last row's id when the endpoint
+ # omits `last_id` (some OpenAI-compatible list responses only return `has_more`). Index the
+ # required primary key directly so any malformed final row — missing `id` or not even a
+ # mapping — fails loudly instead of silently dropping every later page.
+ last_id = data.get("last_id") or items[-1]["id"]
+ if not data.get("has_more") or not last_id:
+ break
+
+ after = last_id
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; merge
+ # dedupes the re-pulled rows on the primary key.
+ resumable_source_manager.save_state(NebiusAIResumeConfig(after=after))
+
+
+def nebius_ai_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NebiusAIResumeConfig],
+) -> SourceResponse:
+ config = NEBIUS_AI_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ # These OpenAI-style list endpoints return newest-first. sort_mode is inert while every stream
+ # is full-refresh (no incremental watermark), but declaring the true order keeps resume/
+ # watermark semantics correct if a server-side time filter is ever added.
+ sort_mode="desc",
+ 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/nebius_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/settings.py
new file mode 100644
index 000000000000..98642d17ba39
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/settings.py
@@ -0,0 +1,58 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Nebius AI Studio (Token Factory) exposes an OpenAI-compatible REST API. The extractable metadata
+# streams mirror OpenAI's object-management endpoints; the chat/embeddings/rerank endpoints are
+# real-time inference and carry no listable data, so they are intentionally omitted.
+#
+# None of these list endpoints document (or, when probed, honor) a server-side timestamp filter, so
+# every stream ships full-refresh only. Pagination is OpenAI-style cursor pagination (`after`/`limit`
+# with `has_more`/`last_id`), which is what makes the source resumable within a run.
+
+
+@dataclass
+class NebiusAIEndpointConfig:
+ name: str
+ path: str
+ # Stable created-style field used for datetime partitioning. Every object carries a Unix-epoch
+ # creation timestamp that never changes, unlike status/updated fields.
+ partition_key: Optional[str] = None
+ # OpenAI-style cursor pagination (`after`/`limit`). `/models` returns the full list in one
+ # response, so it opts out.
+ paginated: bool = True
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+
+
+NEBIUS_AI_ENDPOINTS: dict[str, NebiusAIEndpointConfig] = {
+ "models": NebiusAIEndpointConfig(
+ name="models",
+ path="/models",
+ partition_key="created",
+ paginated=False,
+ ),
+ "files": NebiusAIEndpointConfig(
+ name="files",
+ path="/files",
+ partition_key="created_at",
+ ),
+ "batches": NebiusAIEndpointConfig(
+ name="batches",
+ path="/batches",
+ partition_key="created_at",
+ ),
+ "fine_tuning_jobs": NebiusAIEndpointConfig(
+ name="fine_tuning_jobs",
+ path="/fine_tuning/jobs",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(NEBIUS_AI_ENDPOINTS.keys())
+
+# No endpoint advertises incremental fields: the API has no server-side timestamp filter, so an
+# "incremental" sync would still page through the whole list every run. Kept for parity with the
+# per-endpoint schema wiring and to make the full-refresh posture explicit.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in NEBIUS_AI_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/source.py
index 4804ac0ae0c9..b9c226fddd52 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/source.py
@@ -1,19 +1,43 @@
-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 NebiusAISourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.nebius_ai import (
+ NebiusAIResumeConfig,
+ nebius_ai_source,
+ validate_credentials as validate_nebius_ai_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ NEBIUS_AI_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class NebiusAISource(SimpleSource[NebiusAISourceConfig]):
+class NebiusAISource(ResumableSource[NebiusAISourceConfig, NebiusAIResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.NEBIUSAI
@@ -24,7 +48,91 @@ class NebiusAISource(SimpleSource[NebiusAISourceConfig]):
name=SchemaExternalDataSourceType.NEBIUS_AI,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Nebius AI",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Nebius AI Studio (Token Factory) API key to pull your Nebius inference platform metadata into the PostHog Data warehouse.
+
+You can create an API key in the [Nebius AI Studio console](https://studio.nebius.com/settings/api-keys). A key with read access is enough to sync models, files, batches, and fine-tuning jobs.""",
iconPath="/static/services/nebius_ai.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/nebius-ai",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or expired key surfaces as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.
+ # Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.tokenfactory.nebius.com": "Your Nebius AI API key is invalid or has expired. Create a new key in the Nebius AI Studio console, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.tokenfactory.nebius.com": "Your Nebius AI API key does not have the permissions needed to sync this data. Grant read access to the key, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: NebiusAISourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = NEBIUS_AI_ENDPOINTS[endpoint]
+ # Every stream is full-refresh: the API exposes no server-side timestamp filter, so
+ # incremental would page the whole list every run at no cost saving.
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ 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: NebiusAISourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Forward the transport result verbatim so transient failures and permission errors keep
+ # their distinct messages instead of collapsing into a misleading "invalid key".
+ return validate_nebius_ai_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NebiusAIResumeConfig]:
+ # Namespace resume state by schema so sibling endpoints in the same job never share a cursor.
+ return ResumableSourceManager[NebiusAIResumeConfig](inputs, NebiusAIResumeConfig).with_namespace(
+ inputs.schema_name
+ )
+
+ def source_for_pipeline(
+ self,
+ config: NebiusAISourceConfig,
+ resumable_source_manager: ResumableSourceManager[NebiusAIResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return nebius_ai_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/test_nebius_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/test_nebius_ai.py
new file mode 100644
index 000000000000..61fa23d1be87
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/test_nebius_ai.py
@@ -0,0 +1,277 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai import nebius_ai
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.nebius_ai import (
+ NEBIUS_AI_BASE_URL,
+ NebiusAIResumeConfig,
+ _build_url,
+ get_rows,
+ nebius_ai_source,
+ validate_credentials,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: NebiusAIResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[NebiusAIResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> NebiusAIResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: NebiusAIResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ endpoint: str,
+ pages: dict[str, Any],
+) -> list[dict]:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(nebius_ai, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="nbk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestBuildUrl:
+ def test_no_params_returns_bare_path(self) -> None:
+ assert _build_url("/models", {}) == f"{NEBIUS_AI_BASE_URL}/models"
+
+ def test_params_are_urlencoded(self) -> None:
+ # `after` cursors are opaque ids that can contain characters needing encoding.
+ assert _build_url("/batches", {"limit": 100, "after": "batch abc"}) == (
+ f"{NEBIUS_AI_BASE_URL}/batches?limit=100&after=batch+abc"
+ )
+
+
+class TestValidateCredentials:
+ def test_valid_key_returns_ok(self) -> None:
+ response = MagicMock()
+ response.ok = True
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(nebius_ai, "make_tracked_session", return_value=session):
+ assert validate_credentials("nbk_test") == (True, None)
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_auth_failure_is_rejected_with_message(self, _name: str, status_code: int) -> None:
+ response = MagicMock()
+ response.ok = False
+ response.status_code = status_code
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(nebius_ai, "make_tracked_session", return_value=session):
+ ok, message = validate_credentials("nbk_test")
+ assert ok is False
+ assert message
+
+ @parameterized.expand([("network_error", None), ("server_error", 503), ("rate_limited", 429)])
+ def test_transient_failure_is_not_reported_as_invalid_key(self, _name: str, status_code: int | None) -> None:
+ # A blip must never be surfaced as an invalid key — that would send the user to rotate a good one.
+ session = MagicMock()
+ if status_code is None:
+ session.get.side_effect = requests.ConnectionError("boom")
+ else:
+ response = MagicMock()
+ response.ok = False
+ response.status_code = status_code
+ session.get.return_value = response
+ with patch.object(nebius_ai, "make_tracked_session", return_value=session):
+ ok, message = validate_credentials("nbk_test")
+ assert ok is False
+ assert message is not None
+ assert "invalid" not in message.lower()
+
+ def test_probe_redacts_key_and_disables_redirects(self) -> None:
+ # The key must stay out of captured samples, and a 30x must not replay the bearer token.
+ session = MagicMock()
+ session.get.return_value = MagicMock(ok=True)
+ with patch.object(nebius_ai, "make_tracked_session", return_value=session) as make_session:
+ validate_credentials("nbk_secret")
+ make_session.assert_called_once_with(redact_values=("nbk_secret",), allow_redirects=False)
+
+
+class TestNonPaginatedEndpoint:
+ def test_models_yields_full_list_in_one_batch(self, monkeypatch: Any) -> None:
+ # /models returns the whole list in a single response; it must not be paged with after/limit.
+ pages = {
+ f"{NEBIUS_AI_BASE_URL}/models": {
+ "object": "list",
+ "data": [
+ {"id": "meta-llama/Llama-3.3-70B", "created": 1700000000, "owned_by": "nebius"},
+ {"id": "deepseek-ai/DeepSeek-V3", "created": 1710000000, "owned_by": "nebius"},
+ ],
+ },
+ }
+ manager = _FakeResumableManager()
+ rows = _collect(manager, monkeypatch, "models", pages)
+ assert [r["id"] for r in rows] == ["meta-llama/Llama-3.3-70B", "deepseek-ai/DeepSeek-V3"]
+ # A single-shot endpoint has nothing to resume from, so it must never persist a cursor.
+ assert manager.saved == []
+
+ def test_models_empty_list_yields_nothing(self, monkeypatch: Any) -> None:
+ pages = {f"{NEBIUS_AI_BASE_URL}/models": {"object": "list", "data": []}}
+ rows = _collect(_FakeResumableManager(), monkeypatch, "models", pages)
+ assert rows == []
+
+
+class TestCursorPagination:
+ def test_follows_after_cursor_until_has_more_false(self, monkeypatch: Any) -> None:
+ pages = {
+ f"{NEBIUS_AI_BASE_URL}/batches?limit=100": {
+ "data": [{"id": "b1", "created_at": 1}, {"id": "b2", "created_at": 2}],
+ "has_more": True,
+ "last_id": "b2",
+ },
+ f"{NEBIUS_AI_BASE_URL}/batches?limit=100&after=b2": {
+ "data": [{"id": "b3", "created_at": 3}],
+ "has_more": False,
+ "last_id": "b3",
+ },
+ }
+ manager = _FakeResumableManager()
+ rows = _collect(manager, monkeypatch, "batches", pages)
+ assert [r["id"] for r in rows] == ["b1", "b2", "b3"]
+ # State is saved only after a page that has a successor, so exactly one cursor persists here.
+ assert manager.saved == [NebiusAIResumeConfig(after="b2")]
+
+ def test_falls_back_to_last_item_id_when_last_id_absent(self, monkeypatch: Any) -> None:
+ # Some OpenAI-compatible responses only return has_more; the cursor must come from the row id.
+ pages = {
+ f"{NEBIUS_AI_BASE_URL}/files?limit=100": {
+ "data": [{"id": "f1", "created_at": 1}],
+ "has_more": True,
+ },
+ f"{NEBIUS_AI_BASE_URL}/files?limit=100&after=f1": {
+ "data": [{"id": "f2", "created_at": 2}],
+ "has_more": False,
+ },
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "files", pages)
+ assert [r["id"] for r in rows] == ["f1", "f2"]
+
+ def test_missing_primary_key_on_paginated_page_fails_loudly(self, monkeypatch: Any) -> None:
+ # A page that claims has_more but whose final row is missing its `id` must raise, not silently
+ # drop every later page by treating the malformed page as terminal.
+ pages = {
+ f"{NEBIUS_AI_BASE_URL}/files?limit=100": {
+ "data": [{"created_at": 1}],
+ "has_more": True,
+ },
+ }
+ with pytest.raises(KeyError):
+ _collect(_FakeResumableManager(), monkeypatch, "files", pages)
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ pages = {
+ f"{NEBIUS_AI_BASE_URL}/fine_tuning/jobs?limit=100&after=j5": {
+ "data": [{"id": "j6", "created_at": 6}],
+ "has_more": False,
+ "last_id": "j6",
+ },
+ }
+ manager = _FakeResumableManager(NebiusAIResumeConfig(after="j5"))
+ rows = _collect(manager, monkeypatch, "fine_tuning_jobs", pages)
+ # Resuming must start at the saved cursor, not re-fetch the first page.
+ assert [r["id"] for r in rows] == ["j6"]
+
+
+class TestSessionHardening:
+ def test_get_rows_session_redacts_key_and_disables_redirects(self, monkeypatch: Any) -> None:
+ # The long-lived paging session must mask the key and refuse redirects so a 30x can't replay
+ # the bearer token to another origin.
+ monkeypatch.setattr(nebius_ai, "_fetch_page", lambda *_a, **_k: {"data": []})
+ make_session = MagicMock(return_value=MagicMock())
+ monkeypatch.setattr(nebius_ai, "make_tracked_session", make_session)
+ list(
+ get_rows(
+ api_key="nbk_secret",
+ endpoint="models",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+ make_session.assert_called_once_with(redact_values=("nbk_secret",), allow_redirects=False)
+
+
+class TestFetchPage:
+ @parameterized.expand([("rate_limited", 429), ("bad_gateway", 502), ("server_error", 500)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(nebius_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(nebius_ai.NebiusAIRetryableError):
+ nebius_ai._fetch_page(session, f"{NEBIUS_AI_BASE_URL}/models", {}, MagicMock())
+ assert session.get.call_count == 5
+
+ def test_client_error_raises_for_status(self) -> None:
+ response = MagicMock()
+ response.status_code = 401
+ response.ok = False
+ response.raise_for_status.side_effect = requests.HTTPError("401", response=response)
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(requests.HTTPError):
+ nebius_ai._fetch_page(session, f"{NEBIUS_AI_BASE_URL}/models", {}, MagicMock())
+
+ def test_transient_error_retried_then_succeeds(self) -> None:
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"data": []}
+ session = MagicMock()
+ session.get.side_effect = [requests.ReadTimeout("timeout"), good]
+ with patch.object(nebius_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = nebius_ai._fetch_page(session, f"{NEBIUS_AI_BASE_URL}/models", {}, MagicMock())
+ assert result == {"data": []}
+ assert session.get.call_count == 2
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("models", "created", False),
+ ("files", "created_at", True),
+ ("batches", "created_at", True),
+ ("fine_tuning_jobs", "created_at", True),
+ ]
+ )
+ def test_partition_and_pk_per_endpoint(self, endpoint: str, partition_key: str, _paginated: bool) -> None:
+ response = nebius_ai_source(
+ api_key="nbk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ # These OpenAI-style list endpoints return newest-first.
+ assert response.sort_mode == "desc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/test_nebius_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/test_nebius_ai_source.py
new file mode 100644
index 000000000000..9bfddde23936
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/test_nebius_ai_source.py
@@ -0,0 +1,138 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.nebius_ai import NebiusAIResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.source import NebiusAISource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestNebiusAISourceConfig:
+ def test_source_type(self) -> None:
+ assert NebiusAISource().source_type == ExternalDataSourceType.NEBIUSAI
+
+ def test_config_has_single_api_key_password_field(self) -> None:
+ fields = NebiusAISource().get_source_config.fields
+ assert [f.name for f in fields] == ["api_key"]
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.type == "password"
+ assert field.required is True
+
+ def test_docs_url_matches_published_doc_slug(self) -> None:
+ # docsUrl must match the posthog.com doc filename so the docs link resolves.
+ assert NebiusAISource().get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/nebius-ai"
+
+
+class TestNebiusAISchemas:
+ def test_exposes_expected_endpoints(self) -> None:
+ schemas = NebiusAISource().get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert {s.name for s in schemas} == {"models", "files", "batches", "fine_tuning_jobs"}
+
+ def test_every_endpoint_is_full_refresh_only(self) -> None:
+ # No endpoint has a server-side timestamp filter, so incremental/append must stay off to
+ # avoid advertising a mode that would cost the same as a full refresh every run.
+ for schema in NebiusAISource().get_schemas(MagicMock(), team_id=1):
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_names_filter_narrows_the_list(self) -> None:
+ schemas = NebiusAISource().get_schemas(MagicMock(), team_id=1, names=["files"])
+ assert [s.name for s in schemas] == ["files"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog with no I/O, so the public docs table catalog can render.
+ source = NebiusAISource()
+ assert source.lists_tables_without_credentials is True
+ assert {t["name"] for t in source.get_documented_tables()} == set(ENDPOINTS)
+
+
+class TestNebiusAICanonicalDescriptions:
+ def test_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = NebiusAISource().get_canonical_descriptions()
+ assert set(descriptions) == set(ENDPOINTS)
+ assert all("id" in descriptions[name].get("columns", {}) for name in ENDPOINTS)
+
+
+class TestNebiusAIValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid", (True, None)),
+ ("invalid", (False, "Your Nebius AI API key is invalid or has expired.")),
+ ("transient", (False, "Could not reach Nebius AI: boom")),
+ ]
+ )
+ def test_validate_credentials_forwards_transport_result(self, _name: str, transport_result: tuple) -> None:
+ # The source must forward the transport verdict verbatim so transient and permission messages
+ # are not collapsed into a generic "invalid key".
+ config = MagicMock()
+ config.api_key = "nbk_test"
+ with patch.object(source_module, "validate_nebius_ai_credentials", return_value=transport_result):
+ assert NebiusAISource().validate_credentials(config, team_id=1) == transport_result
+
+
+class TestNebiusAINonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.tokenfactory.nebius.com/v1/models"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.tokenfactory.nebius.com/v1/batches"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ errors = NebiusAISource().get_non_retryable_errors()
+ assert any(key in observed_error for key in errors)
+
+ @parameterized.expand(
+ [
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://api.tokenfactory.nebius.com/v1/files",
+ ),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.tokenfactory.nebius.com"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed_error: str) -> None:
+ errors = NebiusAISource().get_non_retryable_errors()
+ assert not any(key in observed_error for key in errors)
+
+
+class TestNebiusAIResumableWiring:
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = NebiusAISource().get_resumable_source_manager(inputs)
+ assert manager._data_class is NebiusAIResumeConfig
+
+ def test_source_for_pipeline_forwards_api_key_and_schema(self) -> None:
+ config = MagicMock()
+ config.api_key = "nbk_test"
+ inputs = MagicMock()
+ inputs.schema_name = "batches"
+ manager = MagicMock()
+
+ with patch.object(source_module, "nebius_ai_source") as mock_source:
+ NebiusAISource().source_for_pipeline(config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "nbk_test"
+ assert kwargs["endpoint"] == "batches"
+ assert kwargs["resumable_source_manager"] is manager
+
+
+class TestNebiusAIRegistration:
+ def test_source_is_registered(self) -> None:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+
+ source = SourceRegistry.get_source(ExternalDataSourceType.NEBIUSAI)
+ assert isinstance(source, NebiusAISource)
+
+ def test_get_resumable_manager_namespace(self) -> None:
+ # Sanity: the manager's data class survives a with_namespace() sibling (used for isolated state).
+ inputs = MagicMock()
+ manager = NebiusAISource().get_resumable_source_manager(inputs)
+ assert manager.with_namespace("models")._data_class is NebiusAIResumeConfig