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 leexi import source (#72635)

Tom Owers49918ba0a191
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 64fbcc516f39..658a53c399f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -323,6 +323,7 @@ the row lists both.
| kustomer | HTTP | requests | ✅ |
| lattice | HTTP | requests | ✅ |
| leadfeeder | HTTP | requests | ✅ |
+| leexi | HTTP | requests + `rest_source.RESTClient` | ✅ |
| lemlist | HTTP | requests | ✅ |
| less_annoying_crm | HTTP | requests | ✅ |
| lightspeed_retail | HTTP | requests | ✅ |
@@ -805,7 +806,6 @@ doesn't conflict with concurrent PRs.
- koyeb
- kyve
- lambda_labs
-- leexi
- lemon_squeezy
- lever
- liana
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/leexi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/leexi.py
index 10320c82ef11..14a377976efc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/leexi.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/leexi.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class LeexiSourceConfig(config.Config):
- pass
+ api_key_id: str
+ api_key_secret: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/canonical_descriptions.py
new file mode 100644
index 000000000000..ab799247212d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/canonical_descriptions.py
@@ -0,0 +1,108 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "calls": {
+ "description": "A recorded call or meeting analyzed by Leexi, including its transcript, AI summary, chapters, speakers, and tags.",
+ "docs_url": "https://docs.public-api.leexi.ai/reference/list-calls",
+ "columns": {
+ "uuid": "Unique identifier of the call.",
+ "title": "Title of the call.",
+ "description": "Description of the call.",
+ "created_at": "When the call record was created in Leexi.",
+ "updated_at": "When the call record was last updated.",
+ "performed_at": "When the call actually took place.",
+ "direction": "Direction of the call (e.g. inbound or outbound).",
+ "duration": "Duration of the call in seconds.",
+ "is_video": "Whether the call was a video call.",
+ "visible": "Whether the call is visible in Leexi.",
+ "locale": "Language locale detected or set for the call.",
+ "leexi_url": "Link to the call page in the Leexi app.",
+ "recording_url": "Link to the call recording.",
+ "transcript_url": "Link to the call transcript.",
+ "source": "Integration slug the call was imported from (e.g. aircall).",
+ "source_id": "Identifier of the call within the source integration.",
+ "simple_transcript": "Plain-text, speaker-labeled transcript of the call.",
+ "summary": "AI-generated summary of the call.",
+ "conversation_type": "Conversation type assigned to the call (uuid, slug, active).",
+ "owner": "User who owns the call (uuid, name, email).",
+ "participating_users": "Leexi users who participated in the call.",
+ "customers": "External participants on the call (uuid, name, email, phone number).",
+ "chapters": "AI-generated chapters with title, text, and start time.",
+ "prompts": "AI prompt completions attached to the call (category, title, completions).",
+ "speakers": "Speaker-level stats including talk duration and longest monologue.",
+ "tags": "Tags applied to the call.",
+ "tasks": "Tasks created from the call.",
+ "audio_archived_at": "When the call audio was archived, if it was.",
+ "video_archived_at": "When the call video was archived, if it was.",
+ "transcript_archived_at": "When the call transcript was archived, if it was.",
+ "completions_archived_at": "When the call AI completions were archived, if they were.",
+ },
+ },
+ "call_notes": {
+ "description": "An AI-generated note attached to a call, from prompts in the summary or text categories, with per-locale translations.",
+ "docs_url": "https://docs.public-api.leexi.ai/reference/list-call-notes",
+ "columns": {
+ "uuid": "Unique identifier of the call note.",
+ "call_uuid": "Unique identifier of the call this note belongs to.",
+ "created_at": "When the note was created.",
+ "updated_at": "When the note was last updated.",
+ "call": "Summary of the call the note belongs to (uuid, timestamps, duration, direction).",
+ "prompt": "Prompt that generated the note (uuid, title, category).",
+ "translations": "Note text per locale, including the original text.",
+ },
+ },
+ "meeting_events": {
+ "description": "A scheduled meeting Leexi tracks for recording, including the meeting link, attendees, and notetaker bot runs.",
+ "docs_url": "https://docs.public-api.leexi.ai/reference/list-meeting-events",
+ "columns": {
+ "uuid": "Unique identifier of the meeting event.",
+ "title": "Title of the meeting.",
+ "organizer": "Organizer of the meeting (email).",
+ "attendees": "Meeting attendees (email).",
+ "meeting_url": "Join link for the meeting.",
+ "meeting_provider": "Meeting platform (e.g. teams_meeting, google_meeting).",
+ "internal": "Whether every attendee belongs to the company.",
+ "direction": "Direction of the meeting (e.g. outbound).",
+ "start_time": "Scheduled start time of the meeting.",
+ "end_time": "Scheduled end time of the meeting.",
+ "description": "Description of the meeting.",
+ "owned": "Whether the API key's company owns the meeting.",
+ "to_record": "Whether Leexi is set to record the meeting.",
+ "bot_scheduled": "Whether the Leexi notetaker bot is scheduled to join.",
+ "bot_running": "Whether the Leexi notetaker bot is currently running.",
+ "bot_runs": "Past notetaker bot runs with start, end, and end reason.",
+ "origin": "How the event was created (calendar, manual, or api).",
+ "created_at": "When the meeting event was created in Leexi.",
+ "updated_at": "When the meeting event was last updated.",
+ "recording_notified": "Whether attendees were notified about the recording.",
+ "active": "Whether the meeting event is active.",
+ },
+ },
+ "users": {
+ "description": "A Leexi user account, with license and team membership.",
+ "docs_url": "https://docs.public-api.leexi.ai/reference/list-users",
+ "columns": {
+ "uuid": "Unique identifier of the user.",
+ "name": "Full name of the user.",
+ "email": "Email address of the user.",
+ "active": "Whether the user account is active.",
+ "license": "License type assigned to the user.",
+ "team": "Team the user belongs to (uuid, name, active).",
+ "created_at": "When the user was created.",
+ "updated_at": "When the user was last updated.",
+ },
+ },
+ "teams": {
+ "description": "A team of users in Leexi.",
+ "docs_url": "https://docs.public-api.leexi.ai/reference/list-teams",
+ "columns": {
+ "uuid": "Unique identifier of the team.",
+ "name": "Name of the team.",
+ "active": "Whether the team is active.",
+ "created_at": "When the team was created.",
+ "updated_at": "When the team was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/leexi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/leexi.py
new file mode 100644
index 000000000000..8fa166016356
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/leexi.py
@@ -0,0 +1,218 @@
+import dataclasses
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from dateutil import parser
+from requests import Response, Session
+from requests.auth import HTTPBasicAuth
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ rename_parent_fields,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.settings import (
+ CALLS_INCREMENTAL_FIELD_NAMES,
+ INCREMENTAL_FIELDS,
+ LEEXI_BASE_URL,
+ LEEXI_ENDPOINTS,
+ PAGE_SIZE,
+ PRIMARY_KEY,
+)
+
+
+class LeexiResumeConfig:
+ # Framework paginator / fan-out resume snapshot for the current endpoint.
+ paginator_state: Optional[dict[str, Any]] = None
+
+
+class LeexiPaginator(PageNumberPaginator):
+ """Page-number paginator for Leexi's 1-based `page` param.
+
+ Responses report `pagination.count` (total items, not pages), which
+ ``PageNumberPaginator.total_path`` can't consume, so stop as soon as a page comes back
+ shorter than the requested size instead of paying an extra empty-page request.
+ """
+
+ def __init__(self, page_size: int = PAGE_SIZE) -> None:
+ super().__init__(base_page=1, page_param="page")
+ self._page_size = page_size
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if self._has_next_page and data is not None and len(data) < self._page_size:
+ self._has_next_page = False
+
+
+def _make_session(api_key_secret: str) -> Session:
+ """Session for all Leexi traffic. The key secret is registered for value-based redaction so it
+ can't leak into logged URLs or samples, and response capture is disabled: `calls` responses
+ carry `simple_transcript`, and call notes and meeting data are arbitrary customer-authored text
+ that can hold proprietary content or secrets the name-based sample scrubbers can't recognise —
+ so nothing lands in the shared HTTP sample store outside the warehouse table's access controls."""
+ return make_tracked_session(redact_values=(api_key_secret,), capture=False)
+
+
+def _to_leexi_timestamp(value: Any) -> str:
+ """Format an incremental cursor value as Leexi's required `YYYY-MM-DDTHH:MM:SS.000Z`."""
+ if isinstance(value, datetime):
+ parsed = value
+ elif isinstance(value, date):
+ parsed = datetime(value.year, value.month, value.day)
+ else:
+ parsed = parser.parse(str(value))
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+
+
+def _resource(
+ name: str,
+ path: str,
+ params: dict[str, Any],
+ write_disposition: Any = "replace",
+) -> EndpointResource:
+ return {
+ "name": name,
+ "table_name": name,
+ "write_disposition": write_disposition,
+ "endpoint": {
+ "path": path,
+ "params": params,
+ "data_selector": "data",
+ "paginator": LeexiPaginator(),
+ },
+ "table_format": "delta",
+ }
+
+
+def _build_resources(
+ endpoint: str,
+ should_use_incremental_field: bool,
+ incremental_field: Optional[str],
+) -> list[str | EndpointResource]:
+ config = LEEXI_ENDPOINTS[endpoint]
+ params: dict[str, Any] = {"items": PAGE_SIZE, **config.extra_params}
+
+ if config.fan_out_parent:
+ parent = LEEXI_ENDPOINTS[config.fan_out_parent]
+ # Parent rows only resolve uuids, so skip its extra params (e.g. transcripts).
+ parent_params: dict[str, Any] = {"items": PAGE_SIZE}
+ if parent.order:
+ parent_params["order"] = parent.order
+ params["call_uuid"] = {"type": "resolve", "resource": parent.name, "field": PRIMARY_KEY}
+ child = _resource(endpoint, config.path, params)
+ child["include_from_parent"] = [PRIMARY_KEY]
+ return [_resource(parent.name, parent.path, parent_params), child]
+
+ if should_use_incremental_field and endpoint in INCREMENTAL_FIELDS:
+ cursor_field = incremental_field or "updated_at"
+ if cursor_field not in CALLS_INCREMENTAL_FIELD_NAMES:
+ raise ValueError(f"Leexi does not support incremental syncs on field: {cursor_field}")
+ # `date_filter` picks which timestamp `from` filters on; ordering ascending on the
+ # same field keeps the pipeline's watermark checkpointing correct (sort_mode="asc").
+ params["date_filter"] = cursor_field
+ params["order"] = f"{cursor_field} asc"
+ params["from"] = {
+ "type": "incremental",
+ "cursor_path": cursor_field,
+ "initial_value": "1970-01-01T00:00:00.000Z",
+ "convert": _to_leexi_timestamp,
+ }
+ return [_resource(endpoint, config.path, params, {"disposition": "merge", "strategy": "upsert"})]
+
+ if config.order:
+ params["order"] = config.order
+ return [_resource(endpoint, config.path, params)]
+
+
+def leexi_source(
+ api_key_id: str,
+ api_key_secret: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[LeexiResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ config = LEEXI_ENDPOINTS[endpoint]
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": LEEXI_BASE_URL,
+ "headers": {"Accept": "application/json"},
+ # Framework Basic auth redacts the key secret from logs and captured samples.
+ "auth": {"type": "http_basic", "username": api_key_id, "password": api_key_secret},
+ "session": _make_session(api_key_secret),
+ },
+ "resources": _build_resources(endpoint, should_use_incremental_field, incremental_field),
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.paginator_state is not None:
+ initial_paginator_state = resume.paginator_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The framework calls this AFTER a page is yielded, so a crash re-yields the last
+ # page (merge dedupes on uuid) rather than skipping it. Persist only while there's
+ # more to fetch; the Redis TTL handles cleanup on completion.
+ if state:
+ resumable_source_manager.save_state(LeexiResumeConfig(paginator_state=state))
+
+ resources = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ target = next(resource for resource in resources if getattr(resource, "name", None) == endpoint)
+
+ if config.fan_out_parent:
+ # Child rows carry the parent id as `_calls_uuid`; expose it as a flat `call_uuid`.
+ target = target.add_map(rename_parent_fields(config.fan_out_parent, {PRIMARY_KEY: "call_uuid"}))
+ primary_keys = ["call_uuid", PRIMARY_KEY]
+ else:
+ primary_keys = [PRIMARY_KEY]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: target,
+ primary_keys=primary_keys,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ sort_mode="asc",
+ # Call rows can carry full transcripts, so keep buffered chunks smaller than the
+ # pipeline defaults to bound worker memory.
+ chunk_size=1000 if endpoint == "calls" else None,
+ chunk_size_bytes=100 * 1024 * 1024 if endpoint == "calls" else None,
+ column_hints=target.column_hints,
+ )
+
+
+def probe_endpoint(api_key_id: str, api_key_secret: str, path: str) -> Optional[int]:
+ """Probe a Leexi list endpoint with the cheapest possible request; returns the HTTP
+ status, or None when the request itself failed."""
+ _ok, status = validate_via_probe(
+ lambda: _make_session(api_key_secret),
+ f"{LEEXI_BASE_URL}{path}?items=1",
+ auth=HTTPBasicAuth(api_key_id, api_key_secret),
+ )
+ return status
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/settings.py
new file mode 100644
index 000000000000..d28a58af4ea4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/settings.py
@@ -0,0 +1,103 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+LEEXI_BASE_URL = "https://public-api.leexi.ai/v1"
+
+# Leexi caps list pages at 100 items (`items` param, default 10).
+PAGE_SIZE = 100
+
+# Every Leexi resource is identified by its `uuid`.
+PRIMARY_KEY = "uuid"
+
+
+@dataclass(frozen=True)
+class LeexiEndpointConfig:
+ name: str
+ # Relative path appended to the API base. The fan-out child carries a `{call_uuid}`
+ # placeholder that the framework binds from the parent row per request.
+ path: str
+ # Stable creation-time field used for datetime partitioning. Never an `updated_at`-style
+ # field — partitions would rewrite on every sync.
+ partition_key: str
+ # Explicit `order` param for endpoints that document one; users/teams document none.
+ order: str | None = None
+ # Static query params sent on every request.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Set for the fan-out child (`call_notes`): the endpoint whose rows resolve the path.
+ fan_out_parent: str | None = None
+
+
+LEEXI_ENDPOINTS: dict[str, LeexiEndpointConfig] = {
+ "calls": LeexiEndpointConfig(
+ name="calls",
+ path="/calls",
+ partition_key="created_at",
+ order="created_at asc",
+ # Opt the plain-text transcript into each call row.
+ extra_params={"with_simple_transcript": "true"},
+ ),
+ "call_notes": LeexiEndpointConfig(
+ name="call_notes",
+ # `call_uuid` is a query param, but the framework binds resolve params via path
+ # placeholders, so it rides in the path template (same pattern as Asana's
+ # `/projects?workspace={workspace_gid}`).
+ path="/call_notes?call_uuid={call_uuid}",
+ partition_key="created_at",
+ fan_out_parent="calls",
+ ),
+ "meeting_events": LeexiEndpointConfig(
+ name="meeting_events",
+ path="/meeting_events",
+ partition_key="created_at",
+ order="created_at asc",
+ ),
+ "users": LeexiEndpointConfig(
+ name="users",
+ path="/users",
+ partition_key="created_at",
+ ),
+ "teams": LeexiEndpointConfig(
+ name="teams",
+ path="/teams",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(LEEXI_ENDPOINTS.keys())
+
+# /calls is the only endpoint with a genuine server-side timestamp filter (`date_filter` +
+# `from`/`to`, orderable by the same fields). /meeting_events only filters on
+# start_time/end_time, which aren't update cursors (a rescheduled or late-created event
+# would be missed), and the remaining endpoints document no timestamp filters — those all
+# ship full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "calls": [
+ incremental_field("updated_at"),
+ incremental_field("created_at"),
+ incremental_field("performed_at"),
+ ],
+}
+
+# `date_filter` and `order` accept exactly these fields on /calls.
+CALLS_INCREMENTAL_FIELD_NAMES = tuple(f["field"] for f in INCREMENTAL_FIELDS["calls"])
+
+# Permission scope each endpoint's requests require on the API key.
+ENDPOINT_SCOPES: dict[str, str] = {
+ "calls": "read_calls",
+ "call_notes": "read_calls",
+ "meeting_events": "read_meeting_events",
+ "users": "read_users",
+ "teams": "read_teams",
+}
+
+# Path probed (with items=1) to check an endpoint's scope. /call_notes requires a
+# `call_uuid`, so its scope is probed via /calls (both need `read_calls`).
+ENDPOINT_PROBE_PATHS: dict[str, str] = {
+ "calls": "/calls",
+ "call_notes": "/calls",
+ "meeting_events": "/meeting_events",
+ "users": "/users",
+ "teams": "/teams",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/source.py
index 112057ee48ea..ec9d17f6b6a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/source.py
@@ -1,19 +1,50 @@
-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,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.leexi import LeexiSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.leexi import (
+ LeexiResumeConfig,
+ leexi_source,
+ probe_endpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.settings import (
+ ENDPOINT_PROBE_PATHS,
+ ENDPOINT_SCOPES,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LeexiSource(SimpleSource[LeexiSourceConfig]):
+class LeexiSource(ResumableSource[LeexiSourceConfig, LeexiResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v1",)
+ default_version = "v1"
+ api_docs_url = "https://docs.public-api.leexi.ai/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LEEXI
@@ -24,7 +55,138 @@ class LeexiSource(SimpleSource[LeexiSourceConfig]):
name=SchemaExternalDataSourceType.LEEXI,
category=DataWarehouseSourceCategory.SALES,
label="Leexi",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["notetaker", "call recording", "conversation intelligence", "transcription"],
+ caption="""Enter a Leexi API key pair to pull your Leexi calls, notes, meeting events, users, and teams into the PostHog Data warehouse.
+
+You can create an API key in Leexi under Settings > Company settings > API keys (requires an admin account).
+
+Grant these permission scopes so every table can sync:
+- `read_calls` (calls and call notes)
+- `read_meeting_events`
+- `read_users`
+- `read_teams`
+""",
iconPath="/static/services/leexi.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/leexi",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key_id",
+ label="API key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key_secret",
+ label="API key secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://public-api.leexi.ai": "Your Leexi API key is invalid or was revoked. Please create a new API key in Leexi and reconnect.",
+ "402 Client Error: Payment Required for url: https://public-api.leexi.ai": "Your Leexi subscription is inactive. Please check your Leexi plan and try again.",
+ "403 Client Error: Forbidden for url: https://public-api.leexi.ai": "Your Leexi API key is missing a required permission scope. Please grant the scopes listed in the connection form and try again.",
+ }
+
+ def get_schemas(
+ self,
+ config: LeexiSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ # call_notes fans out one request per call (50 requests/minute rate limit), and
+ # most note content already rides on each call row — keep it opt-in.
+ should_sync_default={"call_notes": False},
+ )
+
+ def validate_credentials(
+ self, config: LeexiSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ probe_path = ENDPOINT_PROBE_PATHS.get(schema_name, "/users") if schema_name else "/users"
+ status = probe_endpoint(config.api_key_id, config.api_key_secret, probe_path)
+
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Leexi API key is invalid. Please check the key ID and secret."
+ if status == 402:
+ return False, "Your Leexi subscription is inactive. Please check your Leexi plan."
+ if status == 403:
+ if schema_name is None:
+ # The key authenticates but lacks the probe endpoint's scope. Users may
+ # legitimately grant only the scopes for the tables they want to sync, so
+ # don't block source creation — per-table scope status is surfaced in the
+ # schema picker via get_endpoint_permissions.
+ return True, None
+ return False, f"Your Leexi API key is missing the `{ENDPOINT_SCOPES.get(schema_name)}` scope."
+ return False, "Could not connect to the Leexi API. Please try again."
+
+ def get_endpoint_permissions(
+ self, config: LeexiSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ status_by_path: dict[str, Optional[int]] = {}
+ permissions: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ path = ENDPOINT_PROBE_PATHS.get(endpoint)
+ if path is None:
+ permissions[endpoint] = None
+ continue
+ if path not in status_by_path:
+ status_by_path[path] = probe_endpoint(config.api_key_id, config.api_key_secret, path)
+ status = status_by_path[path]
+ # Only real denials count as missing scope — throttles, 5xx, and network blips
+ # must not mark a table unreachable.
+ if status == 403:
+ permissions[endpoint] = f"API key is missing the `{ENDPOINT_SCOPES[endpoint]}` permission scope"
+ elif status == 401:
+ permissions[endpoint] = "API key is invalid"
+ else:
+ permissions[endpoint] = None
+ return permissions
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LeexiResumeConfig]:
+ return ResumableSourceManager[LeexiResumeConfig](inputs, LeexiResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LeexiSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LeexiResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return leexi_source(
+ api_key_id=config.api_key_id,
+ api_key_secret=config.api_key_secret,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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/leexi/tests/test_leexi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/tests/test_leexi.py
new file mode 100644
index 000000000000..5d1cc9928709
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/tests/test_leexi.py
@@ -0,0 +1,278 @@
+import json
+from datetime import UTC, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.leexi import (
+ LeexiResumeConfig,
+ _make_session,
+ _to_leexi_timestamp,
+ leexi_source,
+ probe_endpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.settings import (
+ ENDPOINTS,
+ LEEXI_ENDPOINTS,
+ PAGE_SIZE,
+)
+
+# The source builds its own capture-disabled session and hands it to RESTClient via the client config.
+CLIENT_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.leexi.leexi.make_tracked_session"
+)
+
+
+def _page(items: list[dict[str, Any]], count: int | None = None) -> Response:
+ body = {"data": items, "pagination": {"page": 1, "items": len(items), "count": count or len(items)}}
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _make_manager(resume_state: Optional[LeexiResumeConfig] = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, routes: list[tuple[str, Response]]) -> list[str]:
+ """Wire a mock session that dispatches each request to the first still-unconsumed route whose
+ substring appears in the fully-prepared URL. Returns the list of URLs sent, in order."""
+ session.headers = {}
+ sent_urls: list[str] = []
+ remaining = list(routes)
+
+ def _prepare(request: Any) -> Any:
+ return request.prepare()
+
+ def _send(prepared: Any, **kwargs: Any) -> Response:
+ sent_urls.append(prepared.url)
+ for i, (substr, response) in enumerate(remaining):
+ if substr in prepared.url:
+ remaining.pop(i)
+ return response
+ raise AssertionError(f"no route for {prepared.url}")
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = _send
+ return sent_urls
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+def _source(
+ endpoint: str,
+ manager: mock.MagicMock,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Any:
+ return leexi_source(
+ "key-id",
+ "key-secret",
+ endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ )
+
+
+def _full_page(prefix: str = "u") -> Response:
+ return _page([{"uuid": f"{prefix}{i}", "created_at": "2026-01-01T00:00:00.000Z"} for i in range(PAGE_SIZE)])
+
+
+class TestPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_page_fetches_next_page_and_checkpoints(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire(session, [("page=1", _full_page()), ("page=2", _page([{"uuid": "last"}]))])
+
+ manager = _make_manager()
+ rows = _rows(_source("users", manager))
+
+ assert len(rows) == PAGE_SIZE + 1
+ assert len(urls) == 2
+ query = _query(urls[0])
+ assert query["page"] == ["1"]
+ assert query["items"] == [str(PAGE_SIZE)]
+ # Checkpoint saved after the first (full) page; the terminal short page saves nothing.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == LeexiResumeConfig(paginator_state={"page": 2})
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_short_page_stops_without_extra_request(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire(session, [("/users", _page([{"uuid": "1"}]))])
+
+ manager = _make_manager()
+ rows = _rows(_source("users", manager))
+
+ assert [r["uuid"] for r in rows] == ["1"]
+ assert len(urls) == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire(session, [("page=7", _page([{"uuid": "9"}]))])
+
+ manager = _make_manager(LeexiResumeConfig(paginator_state={"page": 7}))
+ rows = _rows(_source("users", manager))
+
+ assert [r["uuid"] for r in rows] == ["9"]
+ assert _query(urls[0])["page"] == ["7"]
+
+
+class TestCallsIncremental:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_request_filters_and_orders_on_cursor_field(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire(session, [("/calls", _page([{"uuid": "c1"}]))])
+
+ manager = _make_manager()
+ _rows(
+ _source(
+ "calls",
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 15, 12, 30, 45, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ )
+
+ query = _query(urls[0])
+ assert query["date_filter"] == ["updated_at"]
+ assert query["from"] == ["2026-01-15T12:30:45.000Z"]
+ assert query["order"] == ["updated_at asc"]
+
+ @pytest.mark.parametrize("cursor_field", ["created_at", "performed_at"])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_honors_user_chosen_cursor_field(self, MockSession, cursor_field) -> None:
+ session = MockSession.return_value
+ urls = _wire(session, [("/calls", _page([]))])
+
+ manager = _make_manager()
+ _rows(_source("calls", manager, should_use_incremental_field=True, incremental_field=cursor_field))
+
+ query = _query(urls[0])
+ assert query["date_filter"] == [cursor_field]
+ assert query["order"] == [f"{cursor_field} asc"]
+
+ def test_incremental_rejects_unsupported_cursor_field(self) -> None:
+ with pytest.raises(ValueError, match="start_time"):
+ _source("calls", _make_manager(), should_use_incremental_field=True, incremental_field="start_time")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_orders_by_created_at_without_date_filter(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire(session, [("/calls", _page([{"uuid": "c1"}]))])
+
+ manager = _make_manager()
+ _rows(_source("calls", manager))
+
+ query = _query(urls[0])
+ assert query["order"] == ["created_at asc"]
+ assert query["with_simple_transcript"] == ["true"]
+ assert "date_filter" not in query
+ assert "from" not in query
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 1, 15, 12, 30, 45, tzinfo=UTC), "2026-01-15T12:30:45.000Z"),
+ (datetime(2026, 1, 15, 12, 30, 45), "2026-01-15T12:30:45.000Z"),
+ ("2026-01-15T12:30:45.123Z", "2026-01-15T12:30:45.000Z"),
+ ("2026-01-15", "2026-01-15T00:00:00.000Z"),
+ ],
+ )
+ def test_to_leexi_timestamp_formats(self, value, expected) -> None:
+ assert _to_leexi_timestamp(value) == expected
+
+
+class TestCallNotesFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_one_request_per_call_and_injects_call_uuid(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire(
+ session,
+ [
+ ("/calls", _page([{"uuid": "C1"}, {"uuid": "C2"}])),
+ ("call_uuid=C1", _page([{"uuid": "n1"}])),
+ ("call_uuid=C2", _page([{"uuid": "n2"}])),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("call_notes", manager))
+
+ assert [(r["uuid"], r["call_uuid"]) for r in rows] == [("n1", "C1"), ("n2", "C2")]
+ # The parent listing must not pay for transcripts it never surfaces.
+ assert "with_simple_transcript" not in urls[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_no_calls_yields_no_notes(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls = _wire(session, [("/calls", _page([]))])
+
+ manager = _make_manager()
+ assert _rows(_source("call_notes", manager)) == []
+ assert len(urls) == 1
+
+
+class TestSourceResponseMetadata:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_response_metadata_per_endpoint(self, MockSession, endpoint) -> None:
+ response = _source(endpoint, _make_manager())
+
+ assert response.name == endpoint
+ if endpoint == "call_notes":
+ assert response.primary_keys == ["call_uuid", "uuid"]
+ else:
+ assert response.primary_keys == ["uuid"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [LEEXI_ENDPOINTS[endpoint].partition_key]
+ assert response.sort_mode == "asc"
+
+ @pytest.mark.parametrize("config", list(LEEXI_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config) -> None:
+ assert config.partition_key == "created_at"
+
+
+class TestSampleCaptureDisabled:
+ """Leexi call responses carry `simple_transcript`, notes, and free-form customer text; both the
+ sync and probe sessions must disable HTTP sample capture so those bodies never land in the shared
+ sample store outside the warehouse table's access controls."""
+
+ def test_make_session_disables_capture_and_redacts_secret(self) -> None:
+ adapters = list(_make_session("key-secret").adapters.values())
+ assert adapters
+ assert all(adapter._capture is False for adapter in adapters)
+ assert all("key-secret" in adapter._redact_values for adapter in adapters)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_sync_session_created_with_capture_disabled(self, MockSession) -> None:
+ _wire(MockSession.return_value, [("/users", _page([]))])
+ _rows(_source("users", _make_manager()))
+ assert MockSession.call_args.kwargs["capture"] is False
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_probe_session_created_with_capture_disabled(self, MockSession) -> None:
+ probe_endpoint("key-id", "key-secret", "/calls")
+ assert MockSession.call_args.kwargs["capture"] is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/tests/test_leexi_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/tests/test_leexi_source.py
new file mode 100644
index 000000000000..c09a9a618d73
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leexi/tests/test_leexi_source.py
@@ -0,0 +1,182 @@
+import pytest
+from unittest import mock
+
+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.generated_configs.leexi import LeexiSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.leexi import LeexiResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.leexi.source import LeexiSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+PROBE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.leexi.source.probe_endpoint"
+
+
+class TestLeexiSource:
+ def setup_method(self):
+ self.source = LeexiSource()
+ self.team_id = 123
+ self.config = LeexiSourceConfig(api_key_id="key-id", api_key_secret="key-secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.LEEXI
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Leexi"
+ assert config.label == "Leexi"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/leexi.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key_id", "api_key_secret"]
+
+ def test_api_key_secret_field_is_secret_password(self):
+ config = self.source.get_source_config
+ secret_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key_secret"
+ )
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://public-api.leexi.ai/v1/calls?page=1",
+ "402 Client Error: Payment Required for url: https://public-api.leexi.ai/v1/users",
+ "403 Client Error: Forbidden for url: https://public-api.leexi.ai/v1/teams",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://public-api.leexi.ai/v1/calls",
+ "429 Client Error: Too Many Requests for url: https://public-api.leexi.ai/v1/calls",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_only_calls_supports_incremental(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["calls"].supports_incremental
+ assert {f["field"] for f in schemas["calls"].incremental_fields} == {
+ "updated_at",
+ "created_at",
+ "performed_at",
+ }
+ for name in ("call_notes", "meeting_events", "users", "teams"):
+ assert not schemas[name].supports_incremental
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_call_notes_is_opt_in(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["call_notes"].should_sync_default is False
+ assert schemas["calls"].should_sync_default is True
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])
+ assert [schema.name for schema in schemas] == ["calls"]
+
+ @pytest.mark.parametrize(
+ "status, schema_name, expected_valid",
+ [
+ (200, None, True),
+ (401, None, False),
+ (402, None, False),
+ # A key that authenticates but lacks the probe scope must not block source creation.
+ (403, None, True),
+ (403, "users", False),
+ (200, "calls", True),
+ (None, None, False),
+ ],
+ )
+ @mock.patch(PROBE_PATCH)
+ def test_validate_credentials_status_mapping(self, mock_probe, status, schema_name, expected_valid):
+ mock_probe.return_value = status
+
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name)
+
+ assert is_valid is expected_valid
+ assert (message is None) is expected_valid
+
+ @mock.patch(PROBE_PATCH)
+ def test_validate_credentials_probes_schema_specific_path(self, mock_probe):
+ mock_probe.return_value = 200
+ self.source.validate_credentials(self.config, self.team_id, "call_notes")
+ assert mock_probe.call_args.args[2] == "/calls"
+
+ @mock.patch(PROBE_PATCH)
+ def test_endpoint_permissions_marks_missing_scope_and_dedupes_probes(self, mock_probe):
+ mock_probe.side_effect = lambda _id, _secret, path: 403 if path == "/calls" else 200
+
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, list(ENDPOINTS))
+
+ assert permissions["calls"] == "API key is missing the `read_calls` permission scope"
+ assert permissions["call_notes"] == "API key is missing the `read_calls` permission scope"
+ assert permissions["users"] is None
+ assert permissions["teams"] is None
+ assert permissions["meeting_events"] is None
+ # calls and call_notes share the /calls probe: 4 unique paths, not 5 requests.
+ assert mock_probe.call_count == 4
+
+ @pytest.mark.parametrize("status", [429, 500, None])
+ @mock.patch(PROBE_PATCH)
+ def test_endpoint_permissions_ignores_transient_failures(self, mock_probe, status):
+ mock_probe.return_value = status
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["calls"])
+ assert permissions["calls"] is None
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is LeexiResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.leexi.source.leexi_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_leexi_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "calls"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"
+ inputs.incremental_field = "updated_at"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_leexi_source.assert_called_once()
+ kwargs = mock_leexi_source.call_args.kwargs
+ assert kwargs["api_key_id"] == "key-id"
+ assert kwargs["api_key_secret"] == "key-secret"
+ assert kwargs["endpoint"] == "calls"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"
+ assert kwargs["incremental_field"] == "updated_at"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.leexi.source.leexi_source")
+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_leexi_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "calls"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_leexi_source.call_args.kwargs["db_incremental_field_last_value"] is None