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 mistral_ai import source (#70036)

Tom Owers6f763d842389
diff --git a/frontend/public/services/mistral_ai.svg b/frontend/public/services/mistral_ai.svg
new file mode 100644
index 000000000000..92a560df0214
--- /dev/null
+++ b/frontend/public/services/mistral_ai.svg
@@ -0,0 +1,10 @@
+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M3.428 3.4h3.429v3.428H3.428V3.4zm13.714 0h3.43v3.428h-3.43V3.4z" fill="gold" />
+ <path d="M3.428 6.828h6.857v3.429H3.429V6.828zm10.286 0h6.857v3.429h-6.857V6.828z" fill="#FFAF00" />
+ <path d="M3.428 10.258h17.144v3.428H3.428v-3.428z" fill="#FF8205" />
+ <path
+ d="M3.428 13.686h3.429v3.428H3.428v-3.428zm6.858 0h3.429v3.428h-3.429v-3.428zm6.856 0h3.43v3.428h-3.43v-3.428z"
+ fill="#FA500F"
+ />
+ <path d="M0 17.114h10.286v3.429H0v-3.429zm13.714 0H24v3.429H13.714v-3.429z" fill="#E10500" />
+</svg>
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 41cbf86f0634..d0a2db4d492f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -254,6 +254,7 @@ the row lists both.
| meta_ads | HTTP | requests | ✅ |
| metabase | HTTP | requests | ✅ |
| metorial | HTTP | requests | ✅ |
+| mistral_ai | HTTP | requests | ✅ |
| mixmax | HTTP | requests | ✅ |
| mixpanel | HTTP | requests | ✅ |
| mollie | HTTP | requests | ✅ |
@@ -657,7 +658,6 @@ doesn't conflict with concurrent PRs.
- mintlify
- miro
- missive
-- mistral_ai
- mode
- mono
- nasa
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 45b8a5d85f49..bd3137fb3217 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
@@ -2353,7 +2353,7 @@ class MissiveSourceConfig(config.Config):
@config.config
class MistralAISourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/canonical_descriptions.py
new file mode 100644
index 000000000000..6384dbe1d045
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/canonical_descriptions.py
@@ -0,0 +1,111 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the Mistral AI OpenAPI spec (https://docs.mistral.ai/api/). Partial coverage is fine —
+# any column not described here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "models": {
+ "description": "Models available to the workspace: Mistral's base models plus any fine-tuned models you own.",
+ "docs_url": "https://docs.mistral.ai/api/#tag/models",
+ "columns": {
+ "id": "Unique identifier of the model.",
+ "object": 'The object type, always "model".',
+ "created": "The Unix timestamp (in seconds) for when the model was created.",
+ "owned_by": "The organization that owns the model.",
+ "name": "The name of the model.",
+ "description": "A description of the model.",
+ "max_context_length": "The maximum context length the model supports, in tokens.",
+ "type": 'The kind of model card ("base" or "fine-tuned").',
+ },
+ },
+ "files": {
+ "description": "Files uploaded to the workspace (fine-tuning datasets, batch inputs, OCR sources, etc.).",
+ "docs_url": "https://docs.mistral.ai/api/#tag/files",
+ "columns": {
+ "id": "The unique identifier of the file.",
+ "object": 'The object type, always "file".',
+ "bytes": "The size of the file, in bytes.",
+ "created_at": "The Unix timestamp (in seconds) for when the file was created.",
+ "filename": "The name of the uploaded file.",
+ "purpose": "The intended purpose of the file (e.g. fine-tune, ocr, audio, batch).",
+ "sample_type": "The sample type of the file.",
+ "num_lines": "The number of lines in the file.",
+ "mimetype": "The MIME type of the file.",
+ "source": "The source of the file.",
+ },
+ },
+ "fine_tuning_jobs": {
+ "description": "Fine-tuning jobs with status, hyperparameters, trained-token counts, and timestamps.",
+ "docs_url": "https://docs.mistral.ai/api/#tag/fine-tuning",
+ "columns": {
+ "id": "The ID of the fine-tuning job.",
+ "model": "The base model being fine-tuned.",
+ "status": "The current status of the fine-tuning job.",
+ "created_at": "The Unix timestamp (in seconds) for when the job was created.",
+ "modified_at": "The Unix timestamp (in seconds) for when the job was last modified.",
+ "fine_tuned_model": "The name of the fine-tuned model being created (null while the job runs).",
+ "suffix": "Optional user-provided string inserted into the fine-tuned model name.",
+ "trained_tokens": "Total number of tokens trained.",
+ "job_type": "The type of job (e.g. FT for fine-tuning).",
+ "hyperparameters": "The hyperparameters used for the fine-tuning job.",
+ },
+ },
+ "batch_jobs": {
+ "description": "Batch inference jobs with request counts and per-status progress.",
+ "docs_url": "https://docs.mistral.ai/api/#tag/batch",
+ "columns": {
+ "id": "The ID of the batch job.",
+ "object": "The object type.",
+ "input_files": "The IDs of the input files for the batch job.",
+ "endpoint": "The API endpoint the batch job targets.",
+ "model": "The model used for the batch job.",
+ "status": "The current status of the batch job.",
+ "created_at": "The Unix timestamp (in seconds) for when the job was created.",
+ "total_requests": "Total number of requests in the batch.",
+ "completed_requests": "Number of requests that have completed.",
+ "succeeded_requests": "Number of requests that succeeded.",
+ "failed_requests": "Number of requests that failed.",
+ "output_file": "The ID of the output file, when available.",
+ },
+ },
+ "agents": {
+ "description": "Agents defined in the workspace (beta), including model, instructions, and tools.",
+ "docs_url": "https://docs.mistral.ai/api/#tag/beta.agents",
+ "columns": {
+ "id": "The unique identifier of the agent.",
+ "name": "The name of the agent.",
+ "description": "A description of the agent.",
+ "model": "The model backing the agent.",
+ "object": 'The object type, always "agent".',
+ "version": "The version number of the agent.",
+ "created_at": "The ISO 8601 date-time for when the agent was created.",
+ "updated_at": "The ISO 8601 date-time for when the agent was last updated.",
+ },
+ },
+ "conversations": {
+ "description": "Conversations (beta) started against models or agents.",
+ "docs_url": "https://docs.mistral.ai/api/#tag/beta.conversations",
+ "columns": {
+ "id": "The unique identifier of the conversation.",
+ "object": 'The object type, always "conversation".',
+ "name": "The name of the conversation.",
+ "created_at": "The ISO 8601 date-time for when the conversation was created.",
+ "updated_at": "The ISO 8601 date-time for when the conversation was last updated.",
+ },
+ },
+ "libraries": {
+ "description": "Document libraries (beta) used as retrieval knowledge bases.",
+ "docs_url": "https://docs.mistral.ai/api/#tag/beta.libraries",
+ "columns": {
+ "id": "The unique identifier of the library.",
+ "name": "The name of the library.",
+ "created_at": "The ISO 8601 date-time for when the library was created.",
+ "updated_at": "The ISO 8601 date-time for when the library was last updated.",
+ "owner_id": "The identifier of the library owner.",
+ "owner_type": "The type of the library owner.",
+ "total_size": "The total size of the library, in bytes.",
+ "nb_documents": "The number of documents in the library.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/mistral-ai.md b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/mistral-ai.md
new file mode 100644
index 000000000000..d3f4b3716125
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/mistral-ai.md
@@ -0,0 +1,64 @@
+---
+title: Linking Mistral AI as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: MistralAI
+beta: true
+---
+
+<!--
+This user-facing source doc belongs in the posthog.com repo at
+contents/docs/cdp/sources/mistral-ai.md (served at /docs/cdp/sources/mistral-ai and
+/docs/data-warehouse/sources/mistral-ai). It lives beside the source code only because this PR has no
+posthog.com checkout to drop it into — copy it over and delete this note.
+-->
+
+import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"
+import SyncModes from "../\_snippets/sync-modes.mdx"
+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"
+import AlphaRelease from "../\_snippets/alpha-release.mdx"
+
+<AlphaRelease />
+
+Sync your [Mistral AI](https://mistral.ai) platform data into PostHog: available and fine-tuned models,
+uploaded files, fine-tuning jobs, and batch inference jobs (plus beta agents, conversations, and
+libraries). Use it to analyze fine-tuning progress, batch job throughput, and asset history alongside the
+rest of your product data.
+
+## Prerequisites
+
+To connect Mistral AI, you need an account on [La Plateforme](https://console.mistral.ai) with an API
+key. Free-tier keys work, but Mistral applies tighter workspace rate limits to them.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+Provide your Mistral AI **API key**. You can create one in the
+[API Keys](https://console.mistral.ai/api-keys) section of La Plateforme. Mistral keys are long-lived and
+sent as a bearer token; the same key authenticates every table this connector syncs.
+
+## Sync modes
+
+<SyncModes />
+
+Fine-tuning jobs and batch jobs support incremental syncing via their server-side `created_after` filter.
+Models, files, and the beta agents, conversations, and libraries tables have no creation-time filter in
+the API, so they sync as a full refresh each run. Those datasets are small, so full refresh is cheap.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+If the connection fails with an authorization error, confirm the API key is still active in La Plateforme
+and has not been revoked. The beta tables (agents, conversations, libraries) are off by default because
+Mistral marks those endpoint groups as beta and may change their shape; enable them only if you need them.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/mistral_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/mistral_ai.py
new file mode 100644
index 000000000000..0e09ebe3d25a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/mistral_ai.py
@@ -0,0 +1,237 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+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.mistral_ai.settings import (
+ MISTRAL_AI_ENDPOINTS,
+ MistralAIEndpointConfig,
+)
+
+MISTRAL_AI_BASE_URL = "https://api.mistral.ai"
+
+# Offset pagination has no server-signalled end for the bare-array endpoints, so we stop when a page
+# comes back empty. This cap is a backstop against an API that ignores `page` and loops forever.
+MAX_PAGES = 10_000
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class MistralAIRetryableError(Exception):
+ pass
+
+
+class MistralAIUnexpectedResponseError(Exception):
+ """A 2xx response whose body doesn't match any shape we know how to read rows from.
+
+ Deterministic (a wrong data_key, a schema change, or a wrapped-vs-bare mismatch), so it is not
+ retried — we fail the sync loudly rather than treat the un-parseable page as "no more rows" and
+ finish a green sync with data silently missing.
+ """
+
+ pass
+
+
+class MistralAIResumeConfig:
+ # Next 0-indexed page to fetch. Pages already yielded are persisted to staging before a crash,
+ # so resuming mid-endpoint continues from here rather than restarting.
+ page: int = 0
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _format_created_after(value: Any) -> str:
+ """Format an incremental watermark as the ISO 8601 date-time Mistral's `created_after` expects.
+
+ Mistral returns `created`/`created_at` as Unix timestamps (integer seconds), so the stored
+ watermark arrives as an int; convert it to a UTC date-time string.
+ """
+ # bool is a subclass of int, so guard it before the int/float branch — a stray bool would
+ # otherwise be read as a Unix timestamp. Fail loudly rather than emit an invalid param.
+ if isinstance(value, bool):
+ raise ValueError(f"Boolean value {value} cannot be formatted as a created_after timestamp")
+ if isinstance(value, int | float):
+ dt = datetime.fromtimestamp(value, tz=UTC)
+ elif isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ else:
+ return str(value)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _build_base_params(
+ config: MistralAIEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ """Query params shared across every page of one endpoint (excludes page/page_size)."""
+ params: dict[str, Any] = {}
+
+ if config.order_by is not None:
+ order_param, order_value = config.order_by
+ params[order_param] = order_value
+
+ if (
+ config.supports_incremental
+ and should_use_incremental_field
+ and db_incremental_field_last_value is not None
+ and config.created_after_param is not None
+ ):
+ params[config.created_after_param] = _format_created_after(db_incremental_field_last_value)
+
+ return params
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ MistralAIRetryableError,
+ 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, params: dict[str, Any], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (rate limit) and 5xx are transient — retry. Everything else (esp. 401/403) is terminal and
+ # surfaces via raise_for_status so get_non_retryable_errors can permanently fail the sync.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MistralAIRetryableError(f"Mistral AI API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Mistral AI API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _extract_rows(config: MistralAIEndpointConfig, data: Any) -> list[dict[str, Any]]:
+ """Pull the list of rows out of a response body.
+
+ Most endpoints wrap rows in `{"data": [...]}`; /v1/agents and /v1/conversations return a bare
+ JSON array. A bare array is accepted for any endpoint so a wrapped-vs-bare mismatch still syncs
+ instead of silently dropping every row. Anything we can't read a list out of raises rather than
+ returning `[]`, because `get_rows` treats `[]` as end-of-pagination.
+ """
+ if isinstance(data, list):
+ return data
+ if isinstance(data, dict) and config.data_key is not None:
+ rows = data.get(config.data_key)
+ if isinstance(rows, list):
+ return rows
+ raise MistralAIUnexpectedResponseError(
+ f"Mistral AI {config.name}: unexpected response shape (expected a JSON array"
+ f"{f' or object with key {config.data_key!r}' if config.data_key is not None else ''}, "
+ f"got {type(data).__name__})"
+ )
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MistralAIResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = MISTRAL_AI_ENDPOINTS[endpoint]
+ # One session reused across every page so urllib3 keeps the connection alive. `redact_values`
+ # masks the raw API key if a request is sampled into HTTP telemetry (Bearer auth isn't one of
+ # the header names the transport scrubs by default).
+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))
+ base_params = _build_base_params(config, should_use_incremental_field, db_incremental_field_last_value)
+ url = f"{MISTRAL_AI_BASE_URL}{config.path}"
+
+ if not config.paginated:
+ rows = _extract_rows(config, _fetch_page(session, url, base_params, logger))
+ if rows:
+ yield rows
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None else 0
+ if resume is not None:
+ logger.debug(f"Mistral AI: resuming {endpoint} from page {page}")
+
+ while page < MAX_PAGES:
+ params = {**base_params, "page": page, "page_size": config.page_size}
+ rows = _extract_rows(config, _fetch_page(session, url, params, logger))
+ if not rows:
+ break
+
+ yield rows
+ page += 1
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes on the primary key, and full-refresh runs simply re-stage it.
+ resumable_source_manager.save_state(MistralAIResumeConfig(page=page))
+ else:
+ logger.warning(f"Mistral AI: hit page cap ({MAX_PAGES}) for {endpoint}, stopping pagination")
+
+
+def mistral_ai_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MistralAIResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = MISTRAL_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,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ # "asc" where we can guarantee ascending page order (batch jobs force order_by=created);
+ # "desc" where we can't (fine-tuning jobs) so the watermark is only persisted at the end of a
+ # successful run. Full-refresh endpoints ignore sort_mode.
+ sort_mode=config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ # /v1/models is the cheapest authenticated probe: unpaginated, needs no extra scopes.
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{MISTRAL_AI_BASE_URL}/v1/models",
+ headers=_get_headers(api_key),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/settings.py
new file mode 100644
index 000000000000..f5987c3ccb3e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/settings.py
@@ -0,0 +1,127 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class MistralAIEndpointConfig:
+ name: str
+ path: str
+ # Stable creation-time field used for datetime partitioning (never a mutable field like
+ # updated_at/modified_at). `created` on models, `created_at` everywhere else.
+ partition_key: str
+ # Preferred location of the list in the response body. Most endpoints wrap rows in
+ # `{"data": [...]}`; /v1/agents and /v1/conversations return a bare JSON array (`data_key=None`).
+ # `_extract_rows` also accepts a bare array regardless of this setting, so an endpoint that
+ # returns the un-wrapped shape still syncs rather than silently dropping every row.
+ data_key: Optional[str] = "data"
+ # /v1/models is the only list endpoint with no pagination — a single GET returns everything.
+ paginated: bool = True
+ page_size: int = 100
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+ # Server-side incremental filter. Only set where the API documents a genuine created-time
+ # filter that drops older rows (verified against the published OpenAPI spec: the param is a
+ # date-time filter described as "results for previous creation times are not displayed").
+ incremental_field: Optional[str] = None
+ incremental_field_type: IncrementalFieldType = IncrementalFieldType.Integer
+ created_after_param: Optional[str] = None
+ # Some endpoints let us force ascending creation order so the incremental watermark advances
+ # monotonically. (param_name, ascending_value) — e.g. batch jobs accept order_by=created.
+ order_by: Optional[tuple[str, str]] = None
+ # How the watermark is persisted for incremental endpoints. "asc" stages the running max after
+ # every page (safe only when the API returns rows in ascending creation order); "desc" persists
+ # the watermark once at the end of a successful sync, so an endpoint whose page order we can't
+ # guarantee never advances the watermark past rows still waiting on later pages.
+ sort_mode: Literal["asc", "desc"] = "asc"
+
+ @property
+ def supports_incremental(self) -> bool:
+ return self.created_after_param is not None
+
+ @property
+ def incremental_fields(self) -> list[IncrementalField]:
+ if self.incremental_field is None:
+ return []
+ return [
+ {
+ "label": self.incremental_field,
+ # Displayed/treated as a datetime, but the underlying column is a Unix timestamp
+ # (integer seconds), matching Mistral's `created`/`created_at` fields.
+ "type": IncrementalFieldType.DateTime,
+ "field": self.incremental_field,
+ "field_type": self.incremental_field_type,
+ }
+ ]
+
+
+MISTRAL_AI_ENDPOINTS: dict[str, MistralAIEndpointConfig] = {
+ # Available base models plus this workspace's fine-tuned models. Unpaginated single GET; each
+ # card carries a Unix `created` timestamp.
+ "models": MistralAIEndpointConfig(
+ name="models",
+ path="/v1/models",
+ partition_key="created",
+ paginated=False,
+ ),
+ # Files uploaded to the workspace (fine-tuning datasets, batch inputs, etc.).
+ "files": MistralAIEndpointConfig(
+ name="files",
+ path="/v1/files",
+ partition_key="created_at",
+ ),
+ # Fine-tuning jobs with status, hyperparameters, trained-token counts, and timestamps.
+ # Incremental via created_after. The endpoint exposes no sort parameter, so page order is not
+ # guaranteed; use "desc" semantics so the watermark is only persisted once the whole run
+ # succeeds, never advancing past older jobs sitting on a later page.
+ "fine_tuning_jobs": MistralAIEndpointConfig(
+ name="fine_tuning_jobs",
+ path="/v1/fine_tuning/jobs",
+ partition_key="created_at",
+ incremental_field="created_at",
+ created_after_param="created_after",
+ sort_mode="desc",
+ ),
+ # Batch inference jobs with request counts and statuses. Incremental via created_after; we pass
+ # order_by=created to force ascending order (the API defaults to -created / newest-first).
+ "batch_jobs": MistralAIEndpointConfig(
+ name="batch_jobs",
+ path="/v1/batch/jobs",
+ partition_key="created_at",
+ incremental_field="created_at",
+ created_after_param="created_after",
+ order_by=("order_by", "created"),
+ ),
+ # Beta. Agents defined in the workspace. Returns a bare JSON array; created_at is an ISO string.
+ # No created-time filter, so full refresh only.
+ "agents": MistralAIEndpointConfig(
+ name="agents",
+ path="/v1/agents",
+ partition_key="created_at",
+ data_key=None,
+ should_sync_default=False,
+ ),
+ # Beta. Conversations. Returns a bare JSON array of model/agent conversations; ISO created_at.
+ "conversations": MistralAIEndpointConfig(
+ name="conversations",
+ path="/v1/conversations",
+ partition_key="created_at",
+ data_key=None,
+ should_sync_default=False,
+ ),
+ # Beta. Document libraries (retrieval knowledge bases); ISO created_at. Kept on the wrapped
+ # default, but `_extract_rows` also accepts a bare array if the beta endpoint returns one.
+ "libraries": MistralAIEndpointConfig(
+ name="libraries",
+ path="/v1/libraries",
+ partition_key="created_at",
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(MISTRAL_AI_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in MISTRAL_AI_ENDPOINTS.items() if config.supports_incremental
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/source.py
index 713652598d08..060d17ea13ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_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 MistralAISourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.mistral_ai import (
+ MistralAIResumeConfig,
+ mistral_ai_source,
+ validate_credentials as validate_mistral_ai_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ MISTRAL_AI_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MistralAISource(SimpleSource[MistralAISourceConfig]):
+class MistralAISource(ResumableSource[MistralAISourceConfig, MistralAIResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MISTRALAI
@@ -24,8 +48,95 @@ class MistralAISource(SimpleSource[MistralAISourceConfig]):
name=SchemaExternalDataSourceType.MISTRAL_AI,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Mistral AI",
- iconPath="/static/services/mistral_ai.png",
- keywords=["llm", "ai", "fine-tuning", "mistral"],
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Mistral AI API key to sync your Mistral AI platform data into the PostHog Data warehouse.
+
+You can create an API key in [La Plateforme](https://console.mistral.ai/api-keys).""",
+ iconPath="/static/services/mistral_ai.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/mistral-ai",
+ keywords=["llm", "ai", "fine-tuning", "mistral"],
+ 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.mistral_ai.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls raise_for_status().
+ # Retrying can never satisfy a credential problem, so permanently fail the sync. Match the
+ # stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.mistral.ai": "Your Mistral AI API key is invalid or has been revoked. Create a new key in La Plateforme, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.mistral.ai": "Your Mistral AI API key is missing the permissions needed to sync this data. Check the key's permissions in La Plateforme, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: MistralAISourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=MISTRAL_AI_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=MISTRAL_AI_ENDPOINTS[endpoint].supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=MISTRAL_AI_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: MistralAISourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_mistral_ai_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Mistral AI API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MistralAIResumeConfig]:
+ return ResumableSourceManager[MistralAIResumeConfig](inputs, MistralAIResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MistralAISourceConfig,
+ resumable_source_manager: ResumableSourceManager[MistralAIResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return mistral_ai_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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/tests/test_mistral_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/tests/test_mistral_ai.py
new file mode 100644
index 000000000000..780d799e4057
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/tests/test_mistral_ai.py
@@ -0,0 +1,257 @@
+from datetime import UTC, date, datetime
+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.mistral_ai import mistral_ai
+from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.mistral_ai import (
+ MistralAIResumeConfig,
+ MistralAIUnexpectedResponseError,
+ _build_base_params,
+ _extract_rows,
+ _format_created_after,
+ get_rows,
+ mistral_ai_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.settings import MISTRAL_AI_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: MistralAIResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[MistralAIResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> MistralAIResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: MistralAIResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestFormatCreatedAfter:
+ @parameterized.expand(
+ [
+ # created/created_at come back as Unix seconds, so the watermark is usually an int.
+ ("unix_int", 1_772_000_000, "2026-02-25T06:13:20Z"),
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T00:00:00Z", "2026-03-04T00:00:00Z"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_created_after(value) == expected
+
+ def test_no_offset_suffix(self) -> None:
+ # A "+00:00" offset instead of "Z" is a common way to produce a value the API rejects.
+ assert "+00:00" not in _format_created_after(datetime(2026, 3, 4, tzinfo=UTC))
+
+ def test_bool_raises(self) -> None:
+ # bool is an int subclass; without an explicit guard it would be read as a Unix timestamp.
+ with pytest.raises(ValueError):
+ _format_created_after(True)
+
+
+class TestBuildBaseParams:
+ def test_batch_jobs_incremental_adds_order_by_and_created_after(self) -> None:
+ # order_by=created forces ascending order (API default is -created); dropping it corrupts the
+ # ascending watermark. Dropping created_after silently reverts incremental to a full refresh.
+ params = _build_base_params(
+ MISTRAL_AI_ENDPOINTS["batch_jobs"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1_772_000_000,
+ )
+ assert params == {"order_by": "created", "created_after": "2026-02-25T06:13:20Z"}
+
+ def test_fine_tuning_incremental_adds_created_after_only(self) -> None:
+ params = _build_base_params(
+ MISTRAL_AI_ENDPOINTS["fine_tuning_jobs"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1_772_000_000,
+ )
+ assert params == {"created_after": "2026-02-25T06:13:20Z"}
+
+ def test_first_sync_has_no_created_after(self) -> None:
+ # No watermark yet: sending created_after=None would 400 or filter everything out.
+ params = _build_base_params(
+ MISTRAL_AI_ENDPOINTS["batch_jobs"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ assert params == {"order_by": "created"}
+
+ @parameterized.expand([("files",), ("agents",), ("libraries",), ("models",)])
+ def test_full_refresh_endpoints_send_no_filter(self, endpoint: str) -> None:
+ params = _build_base_params(
+ MISTRAL_AI_ENDPOINTS[endpoint],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1_772_000_000,
+ )
+ assert params == {}
+
+
+class TestExtractRows:
+ @parameterized.expand(
+ [
+ ("wrapped_data", "files", {"data": [{"id": "a"}], "total": 1}, [{"id": "a"}]),
+ ("bare_list", "agents", [{"id": "a"}, {"id": "b"}], [{"id": "a"}, {"id": "b"}]),
+ # A wrapped endpoint that actually returns a bare array must still sync its rows rather
+ # than silently drop them (Mistral's list shapes aren't uniform across endpoints).
+ ("bare_list_for_wrapped_endpoint", "models", [{"id": "m"}], [{"id": "m"}]),
+ ("empty_wrapped", "files", {"data": []}, []),
+ ("empty_bare", "agents", [], []),
+ ]
+ )
+ def test_extract(self, _name: str, endpoint: str, body: Any, expected: list[dict]) -> None:
+ assert _extract_rows(MISTRAL_AI_ENDPOINTS[endpoint], body) == expected
+
+ @parameterized.expand(
+ [
+ # A 2xx with an unreadable shape must raise, not return [] — get_rows treats [] as the
+ # end of pagination, so a silent [] finishes a green sync with rows missing.
+ ("wrapped_missing_key", "files", {"object": "list"}),
+ ("dict_for_bare_endpoint", "agents", {"data": [{"id": "a"}]}),
+ ("data_key_not_a_list", "files", {"data": {"nested": "object"}}),
+ ]
+ )
+ def test_extract_raises_on_unexpected_shape(self, _name: str, endpoint: str, body: Any) -> None:
+ with pytest.raises(MistralAIUnexpectedResponseError):
+ _extract_rows(MISTRAL_AI_ENDPOINTS[endpoint], body)
+
+
+class TestGetRows:
+ @staticmethod
+ def _run(
+ endpoint: str, manager: _FakeResumableManager, pages_by_index: dict[int, Any], **incremental: Any
+ ) -> tuple[list[dict], list[dict[str, Any]]]:
+ seen_params: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> Any:
+ seen_params.append(params)
+ return pages_by_index[params.get("page", 0)]
+
+ rows: list[dict] = []
+ with (
+ patch.object(mistral_ai, "_fetch_page", fake_fetch),
+ patch.object(mistral_ai, "make_tracked_session", lambda **_: MagicMock()),
+ ):
+ for batch in get_rows(
+ api_key="sk-x",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **incremental,
+ ):
+ rows.extend(batch)
+ return rows, seen_params
+
+ def test_paginates_until_empty_page(self) -> None:
+ # Stopping one page early (e.g. len<page_size heuristic against a clamped page size) drops rows;
+ # not advancing `page` loops forever. Empty-page termination guards both.
+ pages = {
+ 0: {"data": [{"id": "f0"}]},
+ 1: {"data": [{"id": "f1"}]},
+ 2: {"data": []},
+ }
+ rows, seen = self._run("files", _FakeResumableManager(), pages)
+ assert rows == [{"id": "f0"}, {"id": "f1"}]
+ assert [p["page"] for p in seen] == [0, 1, 2]
+
+ def test_unpaginated_endpoint_fetches_once(self) -> None:
+ # /v1/models has no pagination; sending page/page_size or looping would be wrong.
+ pages = {0: {"data": [{"id": "m1"}, {"id": "m2"}]}}
+ rows, seen = self._run("models", _FakeResumableManager(), pages)
+ assert rows == [{"id": "m1"}, {"id": "m2"}]
+ assert len(seen) == 1
+ assert "page" not in seen[0]
+
+ def test_saves_next_page_after_each_yield(self) -> None:
+ # State must be saved AFTER yielding so a crash re-yields the last page rather than skipping it.
+ pages = {0: {"data": [{"id": "f0"}]}, 1: {"data": [{"id": "f1"}]}, 2: {"data": []}}
+ manager = _FakeResumableManager()
+ self._run("files", manager, pages)
+ assert [c.page for c in manager.saved] == [1, 2]
+
+ def test_resumes_from_saved_page(self) -> None:
+ # Resuming re-runs earlier pages would duplicate (or, with replace, waste) work; page 0 must be skipped.
+ pages = {1: {"data": [{"id": "f1"}]}, 2: {"data": []}}
+ manager = _FakeResumableManager(MistralAIResumeConfig(page=1))
+ rows, seen = self._run("files", manager, pages)
+ assert rows == [{"id": "f1"}]
+ assert [p["page"] for p in seen] == [1, 2]
+
+ def test_bare_array_endpoint_paginates(self) -> None:
+ pages = {0: [{"id": "a0"}], 1: []}
+ rows, _ = self._run("agents", _FakeResumableManager(), pages)
+ assert rows == [{"id": "a0"}]
+
+
+class TestFetchPageRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_statuses_are_retried(self, _name: str, status: int) -> None:
+ bad = MagicMock(status_code=status)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"data": []}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(mistral_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = mistral_ai._fetch_page(session, "https://api.mistral.ai/v1/files", {}, MagicMock())
+
+ assert result == {"data": []}
+ assert session.get.call_count == 2
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_client_errors_are_not_retried(self, _name: str, status: int) -> None:
+ # A credential error must surface immediately (so get_non_retryable_errors fails the sync),
+ # never spin through the retry budget.
+ resp = MagicMock(status_code=status, ok=False, text="nope")
+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=resp)
+ session = MagicMock()
+ session.get.return_value = resp
+
+ with pytest.raises(requests.HTTPError):
+ mistral_ai._fetch_page(session, "https://api.mistral.ai/v1/files", {}, MagicMock())
+ assert session.get.call_count == 1
+
+ def test_transient_error_reraised_after_cap(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("reset")
+ with patch.object(mistral_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(requests.ConnectionError):
+ mistral_ai._fetch_page(session, "https://api.mistral.ai/v1/files", {}, MagicMock())
+ assert session.get.call_count == 5
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ # batch jobs force ascending order (order_by=created), so the watermark can advance per
+ # page; fine-tuning has no sort param, so it must persist the watermark only at run end.
+ ("models", "created", ["id"], "asc"),
+ ("files", "created_at", ["id"], "asc"),
+ ("batch_jobs", "created_at", ["id"], "asc"),
+ ("fine_tuning_jobs", "created_at", ["id"], "desc"),
+ ]
+ )
+ def test_partitioning_and_keys(
+ self, endpoint: str, partition_key: str, primary_keys: list[str], sort_mode: str
+ ) -> None:
+ response = mistral_ai_source(
+ api_key="sk-x",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ assert response.sort_mode == sort_mode
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/tests/test_mistral_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/tests/test_mistral_ai_source.py
new file mode 100644
index 000000000000..ab61e53f022b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/tests/test_mistral_ai_source.py
@@ -0,0 +1,153 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.mistral_ai import MistralAIResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.source import MistralAISource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> MagicMock:
+ inputs = MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "files")
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)
+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)
+ inputs.incremental_field = overrides.get("incremental_field", None)
+ inputs.logger = MagicMock()
+ return inputs
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert MistralAISource().source_type == ExternalDataSourceType.MISTRALAI
+
+ def test_api_key_field_is_required_secret_password(self) -> None:
+ # A non-secret key field would persist the API key in plaintext job inputs.
+ fields = MistralAISource().get_source_config.fields
+ assert len(fields) == 1
+ api_key = fields[0]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.name == "api_key"
+ assert api_key.required is True
+ assert api_key.secret is True
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+
+ def test_alpha_and_docs_url(self) -> None:
+ config = MistralAISource().get_source_config
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # docsUrl filename must match the posthog.com doc (kebab-case) for the source page to resolve.
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/mistral-ai"
+
+
+class TestGetSchemas:
+ @parameterized.expand(
+ [
+ ("fine_tuning_jobs", True),
+ ("batch_jobs", True),
+ ("files", False),
+ ("models", False),
+ ("agents", False),
+ ("conversations", False),
+ ("libraries", False),
+ ]
+ )
+ def test_incremental_only_where_server_filter_exists(self, endpoint: str, supports_incremental: bool) -> None:
+ # Only fine-tuning and batch jobs expose a server-side created_after filter; the rest must ship
+ # full refresh, never advertise incremental they can't honor.
+ schemas = {s.name: s for s in MistralAISource().get_schemas(MagicMock(), team_id=1)}
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is supports_incremental
+ assert schema.supports_append is supports_incremental
+ if supports_incremental:
+ assert [f["field"] for f in schema.incremental_fields] == ["created_at"]
+ else:
+ assert schema.incremental_fields == []
+
+ @parameterized.expand([("agents", False), ("conversations", False), ("libraries", False), ("files", True)])
+ def test_beta_endpoints_off_by_default(self, endpoint: str, should_sync_default: bool) -> None:
+ schemas = {s.name: s for s in MistralAISource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas[endpoint].should_sync_default is should_sync_default
+
+ def test_names_filter(self) -> None:
+ schemas = MistralAISource().get_schemas(MagicMock(), team_id=1, names=["files", "models"])
+ assert {s.name for s in schemas} == {"files", "models"}
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # lists_tables_without_credentials must stay True so posthog.com renders the Supported tables section.
+ source = MistralAISource()
+ assert source.lists_tables_without_credentials is True
+ tables = source.get_documented_tables()
+ assert {t["name"] for t in tables} == {s.name for s in source.get_schemas(source._placeholder_config(), 0)}
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Mistral AI API key"))])
+ def test_maps_probe_result(self, _name: str, probe: bool, expected: tuple[bool, str | None]) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.source.validate_mistral_ai_credentials",
+ return_value=probe,
+ ):
+ result = MistralAISource().validate_credentials(MagicMock(api_key="sk-x"), team_id=1)
+ assert result == expected
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.mistral.ai/v1/files?page=0"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.mistral.ai/v1/batch/jobs"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ assert any(key in observed for key in MistralAISource().get_non_retryable_errors())
+
+ @parameterized.expand(
+ [
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.mistral.ai/v1/files"),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.mistral.ai/v1/files"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:
+ assert not any(key in observed for key in MistralAISource().get_non_retryable_errors())
+
+
+class TestPipelinePlumbing:
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = MistralAISource().get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MistralAIResumeConfig
+
+ def test_source_for_pipeline_forwards_incremental_inputs(self) -> None:
+ source = MistralAISource()
+ inputs = _make_inputs(
+ schema_name="batch_jobs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1_772_000_000,
+ incremental_field="created_at",
+ )
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.source.mistral_ai_source"
+ ) as mock_source:
+ source.source_for_pipeline(MagicMock(api_key="sk-x"), MagicMock(), inputs)
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["endpoint"] == "batch_jobs"
+ assert kwargs["api_key"] == "sk-x"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1_772_000_000
+
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:
+ # Passing a stale watermark on a full-refresh run would build a bogus created_after filter.
+ source = MistralAISource()
+ inputs = _make_inputs(
+ schema_name="files", should_use_incremental_field=False, db_incremental_field_last_value=1_772_000_000
+ )
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.source.mistral_ai_source"
+ ) as mock_source:
+ source.source_for_pipeline(MagicMock(api_key="sk-x"), MagicMock(), inputs)
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None