: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(warehouse-sources): add nebius ai dataset and fine-tuning detail tables (#115416)
Tom Owers5b51ed907913
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex f6bb0509b94c..b23f8926d370 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -801,8 +801,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py1 products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/nebius_ai.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/nebius_ai/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/netlify/netlify.py1 products/warehouse_sources/backend/temporal/data_imports/sources/netlify/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/new_relic/new_relic.pydiff --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 baa323dca6b9..22abd70d2bf3 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@@ -5789,10 +5789,10 @@ Today (4): `batches`, `files`, `fine_tuning_jobs`, `models`Diffed against: <https://docs.tokenfactory.nebius.com/llms.txt>-- [ ] `GET /v1/datasets (list datasets in project)` — datasets are the training inputs fine-tuning jobs reference; also the lookup resolving dataset ids on jobs (high)-- [ ] `GET /v1/fine_tuning/jobs/{id}/events` — per-job status and training-metric updates over time — the only way to chart loss/progress (high)-- [ ] `GET /v1/fine_tuning/jobs/{id}/checkpoints` — checkpoints produced per job with their metrics, and the ids deployed models map back to (medium)-- [ ] `GET /v1/datasets operations (list/filter operations by attributes)` — dataset operation history (uploads, conversions, fine-tuning ops) with outcomes and errors (medium)+- [x] `GET /v1/datasets (list datasets in project)` — datasets are the training inputs fine-tuning jobs reference; also the lookup resolving dataset ids on jobs (high)+- [x] `GET /v1/fine_tuning/jobs/{id}/events` — per-job status and training-metric updates over time — the only way to chart loss/progress (high)+- [x] `GET /v1/fine_tuning/jobs/{id}/checkpoints` — checkpoints produced per job with their metrics, and the ids deployed models map back to (medium)+- [x] `GET /v1/datasets operations (list/filter operations by attributes)` — dataset operation history (uploads, conversions, fine-tuning ops) with outcomes and errors (medium)- [ ] `GET /v1/dedicated-endpoints` — inventory of deployed dedicated inference endpoints and the models behind them (medium)Note: Nebius Token Factory (formerly AI Studio) is OpenAI-compatible for inference; the non-OpenAI surface is datasets, fine-tuning sub-resources, dedicated endpoints and sandboxes. No usage/billing API is published in the reference, so token-spend cannot be synced. Sandbox endpoints (images, instances, subprocesses) are execution plumbing, not warehouse data.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.pyindex dde2f8e3315e..efba2b00dc0b 100644--- 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@@ -62,4 +62,65 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"trained_tokens": "Total number of billable tokens processed by the job.",},},+ "fine_tuning_job_events": {+ "description": "Status and training-metric updates emitted by each fine-tuning job over time.",+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/list-fine-tuning-events",+ "columns": {+ "id": "Identifier of the event.",+ "fine_tuning_job_id": "ID of the fine-tuning job that emitted the event.",+ "object": "Object type, always 'fine_tuning.job.event'.",+ "created_at": "Unix timestamp (seconds) for when the event was created.",+ "level": "Severity of the event: info, warn, or error.",+ "message": "Human-readable event message.",+ "type": "Kind of event: 'message' for status updates or 'metrics' for training metrics.",+ "data": "Event payload, such as training metrics for a metrics event.",+ },+ },+ "fine_tuning_job_checkpoints": {+ "description": "Checkpoints saved by each fine-tuning job during training, with their metrics.",+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference/fine-tuning/list-fine-tuning-checkpoints",+ "columns": {+ "id": "Identifier of the checkpoint.",+ "fine_tuning_job_id": "ID of the fine-tuning job that produced the checkpoint.",+ "object": "Object type, always 'fine_tuning.job.checkpoint'.",+ "created_at": "Unix timestamp (seconds) for when the checkpoint was created.",+ "fine_tuned_model_checkpoint": "Name of the fine-tuned model checkpoint.",+ "step_number": "Training step at which the checkpoint was saved.",+ "metrics": "Training and validation metrics recorded at the checkpoint.",+ "result_files": "IDs of the files produced for the checkpoint.",+ },+ },+ "datasets": {+ "description": "Datasets in your Nebius AI Studio project, used as inputs for fine-tuning and batch operations.",+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference/datasets/get-a-list-of-datasets-in-project",+ "columns": {+ "id": "Unique identifier for the dataset.",+ "name": "Name of the dataset.",+ "status": "Current status of the dataset (e.g. READY, PENDING, FAILED).",+ "schema": "Column definitions of the dataset.",+ "metadata": "Additional metadata associated with the dataset.",+ "current_version_summary": "Summary of the current dataset version, including row count and size.",+ "folder": "Folder path where the dataset is stored.",+ "type": "Object type, always 'dataset'.",+ "created_at": "Unix timestamp (seconds) for when the dataset was created.",+ "error": "Error message if the dataset is in an error state.",+ "ai_project_id": "AI Studio project ID the dataset belongs to.",+ },+ },+ "operations": {+ "description": "Dataset operations such as file conversions, batch inference, and fine-tuning runs, with their status.",+ "docs_url": "https://docs.tokenfactory.nebius.com/api-reference/datasets/filter-operations-by-attributes",+ "columns": {+ "id": "Unique identifier for the operation.",+ "type": "Type of the operation (e.g. yql, batch_inference, finetuning, file_to_dataset, dataset_to_file, merge).",+ "params": "Parameters specific to the operation type.",+ "src": "Source datasets the operation reads.",+ "dst": "Destination datasets the operation writes.",+ "status": "Current status of the operation (queued, running, succeeded, failed, cancelled, unknown).",+ "created_at": "Unix timestamp (seconds) for when the operation was created.",+ "in_progress_at": "Unix timestamp (seconds) for when the operation started processing.",+ "finished_at": "Unix timestamp (seconds) for when the operation completed.",+ "ai_project_id": "AI Studio project ID the operation belongs to.",+ },+ },}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.pyindex e7dc49475cc7..c3cf76f097e7 100644--- 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@@ -1,7 +1,8 @@import dataclassesfrom collections.abc import Iterator+from datetime import UTC, datetimefrom typing import Any-from urllib.parse import urlencode+from urllib.parse import quote, urlencodeimport requestsfrom structlog.types import FilteringBoundLogger@@ -10,7 +11,11 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.settings import NEBIUS_AI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.nebius_ai.settings import (+ FINE_TUNING_JOBS_PATH,+ NEBIUS_AI_ENDPOINTS,+ NebiusAIEndpointConfig,+)# Token Factory rebrand of the former api.studio.nebius.ai host. OpenAI-compatible surface.NEBIUS_AI_BASE_URL = "https://api.tokenfactory.nebius.com/v1"@@ -23,11 +28,21 @@ class NebiusAIRetryableError(Exception):pass+class NebiusAIPaginationError(Exception):+ pass++[email protected](frozen=True)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+ # Per-job child endpoints: the job whose children are read next, and the `after` cursor of the+ # fine-tuning job page that contains it.+ job_id: str | None = None+ jobs_after: str | None = None+ # `/operations`: ISO 8601 `cursor_time` for the next page.+ cursor_time: str | None = Nonedef _get_headers(api_key: str) -> dict[str, str]:@@ -102,6 +117,164 @@ def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], loreturn response.json()+def _epoch_to_iso(timestamp: int) -> str:+ return datetime.fromtimestamp(timestamp, tz=UTC).isoformat()+++def _get_operation_rows(+ session: requests.Session,+ headers: dict[str, str],+ config: NebiusAIEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NebiusAIResumeConfig],+) -> Iterator[Any]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor_time = resume.cursor_time if resume else None+ previous_page_ids: set[str] = set()++ while True:+ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.params}+ if cursor_time:+ params["cursor_time"] = cursor_time++ data = _fetch_page(session, _build_url(config.path, params), headers, logger)+ items = data.get("data", [])+ # An inclusive cursor returns the boundary rows again.+ new_items = [item for item in items if item["id"] not in previous_page_ids]++ # The API does not document the order or whether `cursor_time` is inclusive. We assume+ # newest-first with the cursor as an upper bound. A full page whose cursor does not move+ # strictly back in time would loop or leave a gap, so fail instead of syncing a partial table.+ has_more = len(items) >= PAGE_SIZE+ next_cursor = _epoch_to_iso(items[-1]["created_at"]) if items else None+ if has_more and cursor_time is not None and next_cursor is not None and next_cursor >= cursor_time:+ raise NebiusAIPaginationError(+ f"Nebius AI {config.name}: cursor_time did not move back in time on a full page, cursor_time={cursor_time}, next_cursor={next_cursor}"+ )++ if has_more:+ resumable_source_manager.save_state(NebiusAIResumeConfig(cursor_time=next_cursor))++ if new_items:+ yield new_items+ else:+ resumable_source_manager.safe_point()++ if not has_more:+ break++ cursor_time = next_cursor+ previous_page_ids = {item["id"] for item in items}+++def _get_job_child_pages(+ session: requests.Session,+ headers: dict[str, str],+ config: NebiusAIEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NebiusAIResumeConfig],+ job_id: str,+ after: str | None,+ jobs_after: str | None,+ position_after_job: NebiusAIResumeConfig | None,+) -> Iterator[Any]:+ path = config.path.format(job_id=quote(job_id, safe=""))++ while True:+ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.params}+ if after:+ params["after"] = after++ data = _fetch_page(session, _build_url(path, params), headers, logger)+ items = data.get("data", [])+ next_after = (data.get("last_id") or items[-1]["id"]) if items else None+ has_more = bool(items and data.get("has_more") and next_after)++ position = (+ NebiusAIResumeConfig(jobs_after=jobs_after, job_id=job_id, after=next_after)+ if has_more+ else position_after_job+ )+ if position is not None:+ resumable_source_manager.save_state(position)++ if items:+ # Events do not carry their job id, so add it for the composite primary key.+ for item in items:+ item.setdefault("fine_tuning_job_id", job_id)+ yield items+ else:+ resumable_source_manager.safe_point()++ if not has_more:+ return++ after = next_after+++def _get_per_job_rows(+ session: requests.Session,+ headers: dict[str, str],+ config: NebiusAIEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NebiusAIResumeConfig],+) -> Iterator[Any]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ jobs_after = resume.jobs_after if resume else None+ resume_job_id = resume.job_id if resume else None+ child_after = resume.after if resume else None++ while True:+ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if jobs_after:+ params["after"] = jobs_after++ jobs_page = _fetch_page(session, _build_url(FINE_TUNING_JOBS_PATH, params), headers, logger)+ job_ids = [job["id"] for job in jobs_page.get("data", [])]+ if not job_ids:+ break++ next_jobs_after = jobs_page.get("last_id") or job_ids[-1]+ has_more_jobs = bool(jobs_page.get("has_more"))++ start = 0+ if resume_job_id is not None:+ if resume_job_id in job_ids:+ start = job_ids.index(resume_job_id)+ else:+ # The job was deleted after the cursor was saved, so read its page from the start.+ child_after = None+ resume_job_id = None++ for index in range(start, len(job_ids)):+ if index + 1 < len(job_ids):+ position_after_job: NebiusAIResumeConfig | None = NebiusAIResumeConfig(+ jobs_after=jobs_after, job_id=job_ids[index + 1]+ )+ elif has_more_jobs:+ position_after_job = NebiusAIResumeConfig(jobs_after=next_jobs_after)+ else:+ position_after_job = None++ yield from _get_job_child_pages(+ session,+ headers,+ config,+ logger,+ resumable_source_manager,+ job_id=job_ids[index],+ after=child_after,+ jobs_after=jobs_after,+ position_after_job=position_after_job,+ )+ child_after = None++ if not has_more_jobs:+ break++ jobs_after = next_jobs_after++def get_rows(api_key: str,endpoint: str,@@ -115,6 +288,14 @@ def get_rows(# to an attacker-controlled host on a 30x.session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ if config.per_fine_tuning_job:+ yield from _get_per_job_rows(session, headers, config, logger, resumable_source_manager)+ return++ if config.time_cursor_paginated:+ yield from _get_operation_rows(session, headers, config, logger, resumable_source_manager)+ return+if not config.paginated:data = _fetch_page(session, _build_url(config.path, {}), headers, logger)items = data.get("data", [])@@ -126,7 +307,7 @@ def get_rows(after = resume.after if resume else Nonewhile True:- params: dict[str, Any] = {"limit": PAGE_SIZE}+ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.params}if after:params["after"] = afterdiff --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.pyindex 98642d17ba39..3521d4a87dc6 100644--- 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@@ -1,5 +1,5 @@from dataclasses import dataclass, field-from typing import Optional+from typing import Any, Optionalfrom products.warehouse_sources.backend.types import IncrementalField@@ -12,7 +12,7 @@ from products.warehouse_sources.backend.types import IncrementalField# with `has_more`/`last_id`), which is what makes the source resumable within a run.-@dataclass+@dataclass(frozen=True)class NebiusAIEndpointConfig:name: strpath: str@@ -22,6 +22,11 @@ class NebiusAIEndpointConfig:# OpenAI-style cursor pagination (`after`/`limit`). `/models` returns the full list in one# response, so it opts out.paginated: bool = True+ # `/operations` pages with an ISO 8601 `cursor_time` instead of `after`, and returns no `has_more`.+ time_cursor_paginated: bool = False+ # Child endpoints listed once per fine-tuning job; `path` carries a `{job_id}` placeholder.+ per_fine_tuning_job: bool = False+ params: dict[str, Any] = field(default_factory=dict)primary_keys: list[str] = field(default_factory=lambda: ["id"])should_sync_default: bool = True@@ -48,8 +53,37 @@ NEBIUS_AI_ENDPOINTS: dict[str, NebiusAIEndpointConfig] = {path="/fine_tuning/jobs",partition_key="created_at",),+ "fine_tuning_job_events": NebiusAIEndpointConfig(+ name="fine_tuning_job_events",+ path="/fine_tuning/jobs/{job_id}/events",+ partition_key="created_at",+ per_fine_tuning_job=True,+ # Event ids are only documented as unique within their job.+ primary_keys=["fine_tuning_job_id", "id"],+ ),+ "fine_tuning_job_checkpoints": NebiusAIEndpointConfig(+ name="fine_tuning_job_checkpoints",+ path="/fine_tuning/jobs/{job_id}/checkpoints",+ partition_key="created_at",+ per_fine_tuning_job=True,+ primary_keys=["fine_tuning_job_id", "id"],+ ),+ "datasets": NebiusAIEndpointConfig(+ name="datasets",+ path="/datasets",+ partition_key="created_at",+ params={"sort_by": "created_at", "sort_order": "desc"},+ ),+ "operations": NebiusAIEndpointConfig(+ name="operations",+ path="/operations",+ partition_key="created_at",+ time_cursor_paginated=True,+ ),}+FINE_TUNING_JOBS_PATH = NEBIUS_AI_ENDPOINTS["fine_tuning_jobs"].path+ENDPOINTS = tuple(NEBIUS_AI_ENDPOINTS.keys())# No endpoint advertises incremental fields: the API has no server-side timestamp filter, so andiff --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.pyindex 8788962e69a1..1ed56d0a5083 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@@ -50,7 +50,7 @@ class NebiusAISource(ResumableSource[NebiusAISourceConfig, NebiusAIResumeConfig]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.""",+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, datasets, dataset operations, and fine-tuning jobs with their events and checkpoints.""",iconPath="/static/services/nebius_ai.png",docsUrl="https://posthog.com/docs/cdp/sources/nebius-ai",fields=cast(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.pyindex aa37572a53e2..f5cbcb29282d 100644--- 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@@ -30,12 +30,16 @@ class _FakeResumableManager:def save_state(self, data: NebiusAIResumeConfig) -> None:self.saved.append(data)+ def safe_point(self) -> None:+ pass+def _collect(manager: _FakeResumableManager,monkeypatch: Any,endpoint: str,pages: dict[str, Any],+ staged_at_yield: list[NebiusAIResumeConfig | None] | None = None,) -> list[dict]:def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:result = pages[url]@@ -53,9 +57,101 @@ def _collect(resumable_source_manager=manager, # type: ignore[arg-type]):rows.extend(batch)+ if staged_at_yield is not None:+ staged_at_yield.append(manager.saved[-1] if manager.saved else None)return rows+JOBS_URL = f"{NEBIUS_AI_BASE_URL}/fine_tuning/jobs"+EVENTS_PAGES = {+ f"{JOBS_URL}?limit=100": {"data": [{"id": "job-a"}, {"id": "job-b"}], "has_more": True, "last_id": "job-b"},+ f"{JOBS_URL}?limit=100&after=job-b": {"data": [{"id": "job-c"}], "has_more": False},+ f"{JOBS_URL}/job-a/events?limit=100": {"data": [{"id": "ev1", "created_at": 3}], "has_more": True},+ f"{JOBS_URL}/job-a/events?limit=100&after=ev1": {"data": [{"id": "ev2", "created_at": 2}], "has_more": False},+ f"{JOBS_URL}/job-b/events?limit=100": {"data": [], "has_more": False},+ f"{JOBS_URL}/job-c/events?limit=100": {"data": [{"id": "ev1", "created_at": 1}], "has_more": False},+}+++class TestPerFineTuningJobEndpoints:+ def test_walks_every_job_page_and_child_page_staging_the_next_position_before_each_yield(+ self, monkeypatch: Any+ ) -> None:+ staged: list[NebiusAIResumeConfig | None] = []+ rows = _collect(_FakeResumableManager(), monkeypatch, "fine_tuning_job_events", EVENTS_PAGES, staged)++ assert [(r["fine_tuning_job_id"], r["id"]) for r in rows] == [+ ("job-a", "ev1"),+ ("job-a", "ev2"),+ ("job-c", "ev1"),+ ]+ assert staged == [+ NebiusAIResumeConfig(job_id="job-a", after="ev1"),+ NebiusAIResumeConfig(job_id="job-b"),+ NebiusAIResumeConfig(jobs_after="job-b"),+ ]++ @parameterized.expand(+ [+ (+ "mid_job_child_page",+ NebiusAIResumeConfig(job_id="job-a", after="ev1"),+ [("job-a", "ev2"), ("job-c", "ev1")],+ ),+ (+ "job_deleted_since_cursor_was_saved",+ NebiusAIResumeConfig(job_id="job-gone", after="ev9"),+ [("job-a", "ev1"), ("job-a", "ev2"), ("job-c", "ev1")],+ ),+ ("later_job_page", NebiusAIResumeConfig(jobs_after="job-b"), [("job-c", "ev1")]),+ ]+ )+ def test_resumes_from_saved_position(+ self, _name: str, state: NebiusAIResumeConfig, expected: list[tuple[str, str]]+ ) -> None:+ with pytest.MonkeyPatch.context() as monkeypatch:+ rows = _collect(_FakeResumableManager(state), monkeypatch, "fine_tuning_job_events", EVENTS_PAGES)+ assert [(r["fine_tuning_job_id"], r["id"]) for r in rows] == expected+++OPERATIONS_URL = f"{NEBIUS_AI_BASE_URL}/operations"+++class TestOperationsTimeCursor:+ def test_pages_by_created_at_cursor_and_drops_repeated_boundary_rows(self) -> None:+ pages = {+ f"{OPERATIONS_URL}?limit=2": {"data": [{"id": "op3", "created_at": 300}, {"id": "op2", "created_at": 200}]},+ f"{OPERATIONS_URL}?limit=2&cursor_time=1970-01-01T00%3A03%3A20%2B00%3A00": {+ "data": [{"id": "op2", "created_at": 200}, {"id": "op1", "created_at": 100}]+ },+ f"{OPERATIONS_URL}?limit=2&cursor_time=1970-01-01T00%3A01%3A40%2B00%3A00": {+ "data": [{"id": "op1", "created_at": 100}]+ },+ }+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(nebius_ai, "PAGE_SIZE", 2)+ rows = _collect(_FakeResumableManager(), monkeypatch, "operations", pages)+ assert [r["id"] for r in rows] == ["op3", "op2", "op1"]++ @parameterized.expand(+ [+ ("same_timestamp_page", [{"id": "op2", "created_at": 200}, {"id": "op1", "created_at": 200}]),+ ("cursor_moves_forward", [{"id": "op4", "created_at": 400}, {"id": "op5", "created_at": 500}]),+ ]+ )+ def test_full_page_whose_cursor_does_not_move_back_fails_the_sync(+ self, _name: str, second_page: list[dict[str, Any]]+ ) -> None:+ pages = {+ f"{OPERATIONS_URL}?limit=2": {"data": [{"id": "op3", "created_at": 300}, {"id": "op2", "created_at": 200}]},+ f"{OPERATIONS_URL}?limit=2&cursor_time=1970-01-01T00%3A03%3A20%2B00%3A00": {"data": second_page},+ }+ with pytest.MonkeyPatch.context() as monkeypatch:+ monkeypatch.setattr(nebius_ai, "PAGE_SIZE", 2)+ with pytest.raises(nebius_ai.NebiusAIPaginationError):+ _collect(_FakeResumableManager(), monkeypatch, "operations", pages)++class TestValidateCredentials:@parameterized.expand([("unauthorized", 401), ("forbidden", 403)])def test_auth_failure_is_rejected_with_message(self, _name: str, status_code: int) -> None:@@ -199,13 +295,17 @@ class TestFetchPage:class TestSourceResponse:@parameterized.expand([- ("models", "created", False),- ("files", "created_at", True),- ("batches", "created_at", True),- ("fine_tuning_jobs", "created_at", True),+ ("models", "created", ["id"]),+ ("files", "created_at", ["id"]),+ ("batches", "created_at", ["id"]),+ ("fine_tuning_jobs", "created_at", ["id"]),+ ("fine_tuning_job_events", "created_at", ["fine_tuning_job_id", "id"]),+ ("fine_tuning_job_checkpoints", "created_at", ["fine_tuning_job_id", "id"]),+ ("datasets", "created_at", ["id"]),+ ("operations", "created_at", ["id"]),])- def test_partition_and_pk_per_endpoint(self, endpoint: str, partition_key: str, _paginated: bool) -> None:+ def test_partition_and_pk_per_endpoint(self, endpoint: str, partition_key: str, primary_keys: list[str]) -> None:response = nebius_ai_source(api_key="nbk_test",endpoint=endpoint,@@ -213,7 +313,7 @@ class TestSourceResponse:resumable_source_manager=MagicMock(),)assert response.name == endpoint- assert response.primary_keys == ["id"]+ assert response.primary_keys == primary_keysassert response.partition_mode == "datetime"assert response.partition_keys == [partition_key]# These OpenAI-style list endpoints return newest-first.