: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(mistral_ai): add conversation entries, library documents, traces and spans tables (#115053)
Tom Owers92aaeb2817eb
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 995a0f4342bb..cd57f18cb4ad 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -800,8 +800,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/metorial/metorial.py1 products/warehouse_sources/backend/temporal/data_imports/sources/metorial/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/mistral_ai.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/mistral_ai/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/mixmax.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.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 9fba3599581b..1ad72c639872 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@@ -5611,10 +5611,10 @@ Today (7): `agents`, `batch_jobs`, `conversations`, `files`, `fine_tuning_jobs`,Diffed against: <https://docs.mistral.ai/openapi.yaml>-- [ ] `conversation messages / history (GET /v1/conversations/{conversation_id}/messages, /history)` — the actual turns inside the conversations we already sync — without them the conversations table has no content (high)+- [x] `conversation messages / history (GET /v1/conversations/{conversation_id}/messages, /history)` — the actual turns inside the conversations we already sync — without them the conversations table has no content (high)- [ ] `organization usage (GET /v1/admin/usage)` — token spend and consumption, the headline metric for an LLM vendor (high)-- [ ] `observability traces and spans (POST /v1/observability/traces/search, /spans/search, GET /v1/observability/traces/{trace_id}/spans)` — per-request latency/cost/error telemetry for agent and workflow runs (high)-- [ ] `library documents (GET /v1/libraries/{library_id}/documents)` — the contents of the libraries we already sync, including processing status (high)+- [x] `observability traces and spans (POST /v1/observability/traces/search, /spans/search, GET /v1/observability/traces/{trace_id}/spans)` — per-request latency/cost/error telemetry for agent and workflow runs (high)+- [x] `library documents (GET /v1/libraries/{library_id}/documents)` — the contents of the libraries we already sync, including processing status (high)- [ ] `admin users and workspaces (GET /v1/admin/users, /v1/admin/workspaces, /v1/admin/workspaces/{uuid}/users)` — lookup and membership tables resolving the user/workspace IDs stamped on jobs and conversations (high)- [ ] `observability chat completion events (POST /v1/observability/chat-completion-events/search)` — per-completion event log for quality and cost analysis (medium)- [ ] `agent versions (GET /v1/agents/{agent_id}/versions)` — version history for the agents we sync, needed to attribute runs to a config (medium)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.pyindex 6384dbe1d045..a157fb914887 100644--- 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@@ -108,4 +108,93 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"nb_documents": "The number of documents in the library.",},},+ "conversation_entries": {+ "description": "Entries (beta) of each conversation in the order they were appended: input and output messages, function calls and results, tool executions, and agent handoffs.",+ "docs_url": "https://docs.mistral.ai/api/#tag/beta.conversations",+ "columns": {+ "id": "The unique identifier of the entry.",+ "conversation_id": "The identifier of the conversation the entry belongs to.",+ "object": 'The object type, always "entry".',+ "type": 'The kind of entry, e.g. "message.input", "message.output", "function.call", "function.result", "tool.execution", or "agent.handoff".',+ "created_at": "The ISO 8601 date-time for when the entry was created.",+ "completed_at": "The ISO 8601 date-time for when the entry was completed.",+ "role": 'The author of a message entry ("user" or "assistant").',+ "content": "The content of a message entry, as a string or a list of content chunks.",+ "agent_id": "The identifier of the agent that produced the entry, if any.",+ "model": "The model that produced the entry, if any.",+ "name": "The name of the function or tool called.",+ "arguments": "The arguments of the function call or tool execution.",+ "tool_call_id": "The identifier of the tool call a function call or result belongs to.",+ },+ },+ "library_documents": {+ "description": "Documents (beta) uploaded to each library, with their processing status.",+ "docs_url": "https://docs.mistral.ai/api/#tag/beta.libraries.documents",+ "columns": {+ "id": "The unique identifier of the document.",+ "library_id": "The identifier of the library the document belongs to.",+ "name": "The name of the document.",+ "mime_type": "The MIME type of the document.",+ "extension": "The file extension of the document.",+ "size": "The size of the document, in bytes.",+ "summary": "A generated summary of the document.",+ "created_at": "The ISO 8601 date-time for when the document was uploaded.",+ "last_processed_at": "The ISO 8601 date-time for when the document was last processed.",+ "number_of_pages": "The number of pages in the document.",+ "process_status": "The processing status of the document.",+ "uploaded_by_id": "The identifier of the user or service that uploaded the document.",+ "uploaded_by_type": "The type of the uploader.",+ "tokens_processing_total": "The total number of tokens used to process the document.",+ "expires_at": "The ISO 8601 date-time after which the document is deleted automatically.",+ },+ },+ "traces": {+ "description": "Observability traces (beta): one row per traced agent or workflow run, with latency, token, and error totals.",+ "docs_url": "https://docs.mistral.ai/api/#tag/beta.observability.traces",+ "columns": {+ "trace_id": "The unique identifier of the trace.",+ "root_span_id": "The identifier of the root span of the trace.",+ "root_span_name": "The name of the root span of the trace.",+ "start_time": "The ISO 8601 date-time for when the trace started.",+ "end_time": "The ISO 8601 date-time for when the trace ended.",+ "duration_ns": "The duration of the trace, in nanoseconds.",+ "workspace_id": "The identifier of the workspace the trace belongs to.",+ "user_id": "The identifier of the user who made the traced requests.",+ "conversation_id": "The identifier of the conversation the trace belongs to.",+ "agent_id": "The identifier of the agent that ran.",+ "agent_name": "The name of the agent that ran.",+ "workflow_name": "The name of the workflow that ran.",+ "status_code": 'The status of the trace ("Error" or "Unset").',+ "error_count": "The number of spans in the trace that ended with an error.",+ "span_count": "The number of spans in the trace.",+ "llm_call_count": "The number of LLM calls in the trace.",+ "tool_call_count": "The number of tool calls in the trace.",+ "input_tokens": "The total number of input tokens used by the trace.",+ "output_tokens": "The total number of output tokens produced by the trace.",+ "models_used": "The models called in the trace.",+ "tools_used": "The tools called in the trace.",+ },+ },+ "spans": {+ "description": "Observability spans (beta): each step of a traced run, such as an LLM call, a tool call, or a retrieval.",+ "docs_url": "https://docs.mistral.ai/api/#tag/beta.observability.spans",+ "columns": {+ "trace_id": "The identifier of the trace the span belongs to.",+ "span_id": "The identifier of the span, unique within its trace.",+ "parent_span_id": "The identifier of the parent span.",+ "span_name": "The name of the span.",+ "span_kind": "The OpenTelemetry kind of the span.",+ "start_time": "The ISO 8601 date-time for when the span started.",+ "end_time": "The ISO 8601 date-time for when the span ended.",+ "duration_ns": "The duration of the span, in nanoseconds.",+ "status_code": 'The status of the span ("Error", "Ok", or "Unset").',+ "error_type": "The type of error the span ended with, if any.",+ "operation_name": "The generative AI operation the span performed.",+ "request_model": "The model requested.",+ "response_model": "The model that answered.",+ "tool_name": "The name of the tool called, for tool spans.",+ "usage_input_tokens": "The number of input tokens used by the span.",+ "usage_output_tokens": "The number of output tokens produced by the span.",+ },+ },}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.mdindex d3f4b3716125..1a7afe8e7f89 100644--- 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@@ -22,8 +22,8 @@ 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+uploaded files, fine-tuning jobs, and batch inference jobs (plus beta agents, conversations and their+entries, libraries and their documents, and observability traces and spans). Use it to analyze fine-tuning progress, batch job throughput, and asset history alongside therest of your product data.## Prerequisites@@ -44,8 +44,9 @@ sent as a bearer token; the same key authenticates every table this connector sy<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.+The beta traces and spans tables support incremental syncing on `start_time`.+Models, files, and the beta agents, conversations, conversation entries, libraries, and library documents+tables have no creation-time filter in the API, so they sync as a full refresh each run.## Configuration@@ -58,7 +59,8 @@ the API, so they sync as a full refresh each run. Those datasets are small, so f## TroubleshootingIf 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+and has not been revoked. The beta tables (agents, conversations, conversation entries, libraries, library documents, traces,+and spans) are off by default becauseMistral 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.pyindex 1d288abb233f..e73514fdecfd 100644--- 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@@ -39,11 +39,15 @@ class MistralAIUnexpectedResponseError(Exception):pass[email protected](frozen=False)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+ # Next observability search cursor, for cursor-paginated endpoints.+ cursor: Optional[str] = None+ # Fan-out position as a shrinking queue of parent ids still to fetch children for.+ remaining_parent_ids: Optional[list[str]] = Nonedef _get_headers(api_key: str) -> dict[str, str]:@@ -80,7 +84,7 @@ def _build_base_params(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] = {}+ params: dict[str, Any] = dict(config.extra_params)if config.order_by is not None:order_param, order_value = config.order_by@@ -110,8 +114,17 @@ def _build_base_params(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)+def _fetch_page(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+ json_body: Optional[dict[str, Any]] = None,+) -> Any:+ if json_body is not None:+ response = session.post(url, params=params, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS)+ else:+ 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.@@ -146,6 +159,132 @@ def _extract_rows(config: MistralAIEndpointConfig, data: Any) -> list[dict[str,)+def _extract_feed(config: MistralAIEndpointConfig, data: Any) -> tuple[list[dict[str, Any]], Optional[str]]:+ """Pull rows and the next cursor out of an observability search response.++ The body is `{<data_key>: {"results": [...], "cursor": ..., "next": ...}}`.+ """+ feed = data.get(config.data_key) if isinstance(data, dict) and config.data_key is not None else None+ rows = feed.get("results") if isinstance(feed, dict) else None+ if not isinstance(rows, list):+ raise MistralAIUnexpectedResponseError(+ f"Mistral AI {config.name}: unexpected response shape (expected an object with "+ f"{config.data_key!r}.results, got {type(data).__name__})"+ )+ cursor = feed.get("cursor") if isinstance(feed, dict) else None+ return rows, cursor or None+++def _get_cursor_rows(+ session: requests.Session,+ config: MistralAIEndpointConfig,+ url: str,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MistralAIResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume is not None else None+ if cursor is not None:+ logger.debug(f"Mistral AI: resuming {config.name} from saved cursor")++ for _ in range(MAX_PAGES):+ params = {**base_params, "page_size": config.page_size}+ if cursor is not None:+ params["cursor"] = cursor+ rows, next_cursor = _extract_feed(config, _fetch_page(session, url, params, logger, json_body={}))+ if not rows:+ return++ if next_cursor is not None:+ resumable_source_manager.save_state(MistralAIResumeConfig(cursor=next_cursor))+ yield rows+ if next_cursor is None or next_cursor == cursor:+ return+ cursor = next_cursor++ logger.warning(f"Mistral AI: hit page cap ({MAX_PAGES}) for {config.name}, stopping pagination")+++def _iter_parent_ids(+ session: requests.Session,+ parent_config: MistralAIEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MistralAIResumeConfig],+) -> Iterator[str]:+ url = f"{MISTRAL_AI_BASE_URL}{parent_config.path}"+ for page in range(MAX_PAGES):+ params = {"page": page, "page_size": parent_config.page_size}+ rows = _extract_rows(parent_config, _fetch_page(session, url, params, logger))+ if not rows:+ return+ for row in rows:+ yield str(row["id"])+ # Nothing has been yielded yet, so a hand-off here restarts the enumeration and loses no rows.+ resumable_source_manager.safe_point()++ logger.warning(f"Mistral AI: hit page cap ({MAX_PAGES}) for {parent_config.name}, stopping pagination")+++def _get_fan_out_rows(+ session: requests.Session,+ config: MistralAIEndpointConfig,+ base_params: dict[str, Any],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MistralAIResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ assert config.parent is not None and config.parent_id_field is not None+ parent_config = MISTRAL_AI_ENDPOINTS[config.parent]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.remaining_parent_ids is not None:+ parent_ids = list(resume.remaining_parent_ids)+ logger.debug(f"Mistral AI: resuming {config.name} with {len(parent_ids)} {config.parent} remaining")+ else:+ # Enumerated up front so the fan-out position can be saved as a shrinking queue.+ parent_ids = list(_iter_parent_ids(session, parent_config, logger, resumable_source_manager))++ while parent_ids:+ parent_id = parent_ids[0]+ remaining = parent_ids[1:]+ parent_ids = remaining+ url = f"{MISTRAL_AI_BASE_URL}{config.path.format(parent_id=parent_id)}"+ try:+ for page in range(MAX_PAGES if config.paginated else 1):+ params = (+ {**base_params, "page": page, "page_size": config.page_size} if config.paginated else base_params+ )+ data = _fetch_page(session, url, params, logger)+ rows = _extract_rows(config, data)+ pagination = data.get("pagination") if isinstance(data, dict) else None+ last_page = (+ not config.paginated+ or not rows+ or (isinstance(pagination, dict) and pagination.get("has_more") is False)+ )++ # Keep this parent at the head until its last page: a resume re-fetches its rows,+ # which merge dedupes.+ resumable_source_manager.save_state(+ MistralAIResumeConfig(remaining_parent_ids=remaining if last_page else [parent_id, *remaining])+ )+ if not rows:+ resumable_source_manager.safe_point()+ break+ yield [{**row, config.parent_id_field: row.get(config.parent_id_field) or parent_id} for row in rows]+ if last_page:+ break+ else:+ logger.warning(f"Mistral AI: hit page cap ({MAX_PAGES}) for {config.name} of {parent_id}")+ except requests.HTTPError as e:+ # The parent can be deleted between enumeration (or a saved queue) and this fetch.+ if e.response is None or e.response.status_code != 404:+ raise+ logger.warning(f"Mistral AI: {config.parent} {parent_id} no longer exists, skipping {config.name}")+ resumable_source_manager.save_state(MistralAIResumeConfig(remaining_parent_ids=remaining))+ resumable_source_manager.safe_point()++def get_rows(api_key: str,endpoint: str,@@ -163,6 +302,14 @@ def get_rows(base_params = _build_base_params(config, should_use_incremental_field, db_incremental_field_last_value)url = f"{MISTRAL_AI_BASE_URL}{config.path}"+ if config.parent is not None:+ yield from _get_fan_out_rows(session, config, base_params, logger, resumable_source_manager)+ return++ if config.pagination == "cursor":+ yield from _get_cursor_rows(session, config, url, base_params, logger, resumable_source_manager)+ return+if not config.paginated:rows = _extract_rows(config, _fetch_page(session, url, base_params, logger))if rows: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.pyindex f5987c3ccb3e..fe264dc5a1e6 100644--- 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@@ -4,7 +4,7 @@ from typing import Literal, Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-@dataclass+@dataclass(frozen=False)class MistralAIEndpointConfig:name: strpath: str@@ -30,6 +30,14 @@ class MistralAIEndpointConfig:# 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+ extra_params: dict[str, str] = field(default_factory=dict)+ # "page" walks 0-indexed `page`/`page_size` until an empty page. "cursor" is the observability+ # search feed: a POST whose body nests rows and the next cursor under `data_key`.+ pagination: Literal["page", "cursor"] = "page"+ # Fan-out child endpoints: `path` holds a `{parent_id}` placeholder filled from each row of the+ # parent endpoint, and the parent id is stamped onto child rows under `parent_id_field`.+ parent: Optional[str] = None+ parent_id_field: Optional[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@@ -47,8 +55,8 @@ class MistralAIEndpointConfig: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.+ # Displayed/treated as a datetime. The underlying column is a Unix timestamp (integer+ # seconds) for the jobs' `created_at`, and an ISO date-time for observability `start_time`."type": IncrementalFieldType.DateTime,"field": self.incremental_field,"field_type": self.incremental_field_type,@@ -118,6 +126,63 @@ MISTRAL_AI_ENDPOINTS: dict[str, MistralAIEndpointConfig] = {partition_key="created_at",should_sync_default=False,),+ # Beta. Every entry (messages, function calls, tool executions, handoffs) of each conversation,+ # in the order appended. /history is a superset of /messages, so only /history is synced. Entry+ # ids are only documented within a conversation, so the key carries the conversation id.+ "conversation_entries": MistralAIEndpointConfig(+ name="conversation_entries",+ path="/v1/conversations/{parent_id}/history",+ partition_key="created_at",+ data_key="entries",+ paginated=False,+ primary_keys=["conversation_id", "id"],+ should_sync_default=False,+ parent="conversations",+ parent_id_field="conversation_id",+ ),+ # Beta. Documents uploaded to each library, with their processing status. No created-time filter.+ "library_documents": MistralAIEndpointConfig(+ name="library_documents",+ path="/v1/libraries/{parent_id}/documents",+ partition_key="created_at",+ primary_keys=["library_id", "id"],+ should_sync_default=False,+ extra_params={"sort_by": "created_at", "sort_order": "asc"},+ parent="libraries",+ parent_id_field="library_id",+ ),+ # Beta. Observability traces (one row per agent/workflow run) with latency, token and error+ # counts. `from` filters on the trace start time. The feed documents no ordering, so the+ # watermark is persisted only at the end of a successful run.+ "traces": MistralAIEndpointConfig(+ name="traces",+ path="/v1/observability/traces/search",+ partition_key="start_time",+ data_key="traces",+ page_size=100,+ primary_keys=["trace_id"],+ should_sync_default=False,+ incremental_field="start_time",+ incremental_field_type=IncrementalFieldType.DateTime,+ created_after_param="from",+ sort_mode="desc",+ pagination="cursor",+ ),+ # Beta. Observability spans across every trace. Span ids are only unique within a trace.+ "spans": MistralAIEndpointConfig(+ name="spans",+ path="/v1/observability/spans/search",+ partition_key="start_time",+ data_key="spans",+ page_size=100,+ primary_keys=["trace_id", "span_id"],+ should_sync_default=False,+ incremental_field="start_time",+ incremental_field_type=IncrementalFieldType.DateTime,+ created_after_param="from",+ sort_mode="desc",+ pagination="cursor",+ ),}ENDPOINTS = tuple(MISTRAL_AI_ENDPOINTS.keys())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.pyindex 2bacc6867028..131dabb8c847 100644--- 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@@ -7,6 +7,14 @@ from unittest.mock import MagicMock, patchimport requestsfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+ route,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mistralai import (+ MistralAISourceConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai import mistral_aifrom products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.mistral_ai import (MistralAIResumeConfig,@@ -18,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_aimistral_ai_source,)from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.settings import MISTRAL_AI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mistral_ai.source import MistralAISourceclass _FakeResumableManager:@@ -210,3 +219,93 @@ class TestSourceResponse:assert response.partition_mode == "datetime"assert response.partition_keys == [partition_key]assert response.sort_mode == sort_mode+++def _driver() -> SourceDriver:+ return SourceDriver(MistralAISource(), MistralAISourceConfig(api_key="sk-x"))+++class TestObservabilitySearch:+ @staticmethod+ def _feed(key: str, ids: list[str], cursor: str | None) -> ScriptedResponse:+ return ScriptedResponse(json={key: {"results": [{"trace_id": i} for i in ids], "cursor": cursor}})++ @parameterized.expand([("traces",), ("spans",)])+ def test_incremental_walk_follows_cursor_and_filters_from(self, endpoint: str) -> None:+ result = _driver().run(+ endpoint,+ [self._feed(endpoint, ["t1", "t2"], "c1"), self._feed(endpoint, ["t3"], None)],+ incremental_field="start_time",+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )++ assert [r["trace_id"] for r in result.rows] == ["t1", "t2", "t3"]+ assert [r.method for r in result.requests] == ["POST", "POST"]+ assert result.params("cursor") == [None, "c1"]+ assert result.params("from") == ["2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"]+ assert result.saved_states == [MistralAIResumeConfig(cursor="c1")]++ def test_resumes_from_saved_cursor(self) -> None:+ result = _driver().run(+ "traces", [self._feed("traces", ["t3"], None)], resume_state=MistralAIResumeConfig(cursor="c1")+ )++ assert result.params("cursor") == ["c1"]+ assert [r["trace_id"] for r in result.rows] == ["t3"]+++class TestFanOut:+ def test_conversation_entries_stamp_parent_and_skip_deleted_conversations(self) -> None:+ result = _driver().run(+ "conversation_entries",+ route(+ {+ "/v1/conversations": [+ ScriptedResponse(json=[{"id": "conv_1"}, {"id": "conv_gone"}]),+ ScriptedResponse(json=[]),+ ],+ "/v1/conversations/conv_1/history": [+ ScriptedResponse(json={"conversation_id": "conv_1", "entries": [{"id": "e1"}, {"id": "e2"}]})+ ],+ "/v1/conversations/conv_gone/history": [ScriptedResponse(status=404, json={"detail": "x"})],+ }+ ),+ )++ assert result.raised is None+ assert result.rows == [{"id": "e1", "conversation_id": "conv_1"}, {"id": "e2", "conversation_id": "conv_1"}]+ assert result.committed_states[-1] == MistralAIResumeConfig(remaining_parent_ids=[])++ def test_library_documents_page_until_has_more_is_false(self) -> None:+ def docs(ids: list[str], has_more: bool) -> ScriptedResponse:+ return ScriptedResponse(+ json={"pagination": {"has_more": has_more}, "data": [{"id": i, "library_id": "lib_1"} for i in ids]}+ )++ result = _driver().run(+ "library_documents",+ route(+ {+ "/v1/libraries": [+ ScriptedResponse(json={"data": [{"id": "lib_1"}]}),+ ScriptedResponse(json={"data": []}),+ ],+ "/v1/libraries/lib_1/documents": [docs(["d1"], True), docs(["d2"], False)],+ }+ ),+ )++ assert [r["id"] for r in result.rows] == ["d1", "d2"]+ doc_requests = [r for r in result.requests if r.path.endswith("/documents")]+ assert [r.param("page") for r in doc_requests] == ["0", "1"]+ assert {r.param("sort_order") for r in doc_requests} == {"asc"}++ def test_resume_skips_enumeration_and_finished_parents(self) -> None:+ result = _driver().run(+ "conversation_entries",+ [ScriptedResponse(json={"conversation_id": "conv_2", "entries": [{"id": "e9"}]})],+ resume_state=MistralAIResumeConfig(remaining_parent_ids=["conv_2"]),+ )++ assert result.paths == ["/v1/conversations/conv_2/history"]+ assert result.rows == [{"id": "e9", "conversation_id": "conv_2"}]