: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(data-warehouse): implement llama_cloud import source (#70712)
Tom Owers2197999b962a
diff --git a/frontend/public/services/llama_cloud.svg b/frontend/public/services/llama_cloud.svgnew file mode 100644index 000000000000..aeae102afbaf--- /dev/null+++ b/frontend/public/services/llama_cloud.svg@@ -0,0 +1,12 @@+<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">+ <path fill="#000" d="M16.8102 0H3.18979C1.42812 0 0 1.42812 0 3.18979V16.8102C0 18.5719 1.42812 20 3.18979 20H16.8102C18.5719 20 20 18.5719 20 16.8102V3.18979C20 1.42812 18.5719 0 16.8102 0Z"/>+ <path fill="url(#llama_cloud_gradient)" d="M15.1999 17.2717s.8825-1.4695-1.1823-2.5221c0 0 .3997 1.5715-.5359 3.0282h-.9612s-.0425-.3062.3636-.4615c.8506-.3275.8847-1.7246.6359-1.8926-.7592-.5104-1.0591-.9463-.8634-2.0563 0 0-1.3142.4806-2.94739.2743-.08506-.0106-.16799.0298-.21052.1042-.08719.151-.26369.4232-.55503.7379 0 0-.07443.8697-.27007 1.4886 0 0 .07443 1.059-.19351 1.8033H7.33175s.01276-.4615.56566-.521c.67624-.0723-.12121-2.1755-.12121-2.1755s-.03403 1.1462-.72302 2.6922h-.87826s0-.4466.44657-.5571c.72515-.1808.40192-1.4865.28496-2.2116-.11696-.7273-.2807-2.0862-.87401-2.8411-.5933-.7549-.89526-.7485-.93142-2.135 0 0-.50398-.79533-.32323-1.84371 0 0-.37639-1.25891.18926-3.11962 0 0-1.33758-.2722-1.3631-.60393-.02765-.33174.0723-.70814.42956-.74004.35725-.03189.88038-.08506.88251-.46145 0-.3764-.45508-.87613-.17225-1.02286.26369-.13823.56991.75279.77193.61244.13184-.09144-.35939-.57204-.03828-.50612.13185.02765 1.2504.39766 1.62892 2.34982.37852 1.95215.22116 3.25571.76768 3.25571s3.04518-.09144 4.50398.26582c1.4588.35725 1.5183.91653 2.1584.75492.6401-.16162 1.3759-.54865 1.7927.86975.3679 1.24827-.6656 1.09087-.6656 1.48217s-.1382.9974.0191 1.3674c.1574.37.0702 1.2631.2084 1.7692.1383.5062.3041.9655-.0085 1.6183 0 0 .1531 1.0994-.1914 1.7034h-.8293s-.0596-.3445.3445-.5061h-.0064Z"/>+ <defs>+ <linearGradient id="llama_cloud_gradient" x1="3.00001" x2="15.0659" y1="2.64966" y2="18.7687" gradientUnits="userSpaceOnUse">+ <stop stop-color="#37D7FA"/>+ <stop offset=".4" stop-color="#4B72FE"/>+ <stop offset=".68" stop-color="#FF8DF2"/>+ <stop offset="1" stop-color="#FF8705"/>+ </linearGradient>+ </defs>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4f28d9cbfd6b..c06c15bffe70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -270,6 +270,7 @@ the row lists both.| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ || linkrunner | HTTP | requests | ✅ || linode | HTTP | requests | ✅ |+| llama_cloud | HTTP | requests | ✅ || lob | HTTP | requests | ✅ || luma | HTTP | requests | ✅ || mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |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.pyindex 8738a2c6887f..0c73f20059a8 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@@ -2424,7 +2424,8 @@ class LinodeSourceConfig(config.Config):@config.configclass LlamaCloudSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["na", "eu"] = config.value(default="na")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/canonical_descriptions.pynew file mode 100644index 000000000000..d1c8b1697015--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/canonical_descriptions.py@@ -0,0 +1,154 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "parse_jobs": {+ "description": "LlamaParse document parsing jobs, one row per parse job with its status and metadata.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/parsing",+ "columns": {+ "id": "Unique identifier for the parse job.",+ "created_at": "Timestamp when the parse job was created.",+ "updated_at": "Timestamp when the parse job was last updated.",+ "project_id": "Identifier of the LlamaCloud project the job belongs to.",+ "status": "Job status: PENDING, RUNNING, COMPLETED, FAILED, or CANCELLED.",+ "error_message": "Error details when the job failed.",+ "name": "Name of the parsed file or job.",+ "tier": "Parse tier (mode) the job ran with.",+ "user_metadata": "Custom key-value metadata attached to the job by the caller.",+ },+ },+ "extract_jobs": {+ "description": "LlamaExtract structured-extraction jobs, one row per extraction run with its configuration and status.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/extraction",+ "columns": {+ "id": "Unique identifier for the extraction job.",+ "created_at": "Timestamp when the extraction job was created.",+ "updated_at": "Timestamp when the extraction job was last updated.",+ "project_id": "Identifier of the LlamaCloud project the job belongs to.",+ "status": "Job status: PENDING, THROTTLED, RUNNING, COMPLETED, FAILED, or CANCELLED.",+ "error_message": "Error details when the job failed.",+ "file_input": "Identifier or reference of the input file the job extracted from.",+ "configuration_id": "Identifier of the extraction configuration (agent) used.",+ },+ },+ "classify_jobs": {+ "description": "Document classification jobs, one row per classify run with its status and result.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/classifier",+ "columns": {+ "id": "Unique identifier for the classify job.",+ "created_at": "Timestamp when the classify job was created.",+ "updated_at": "Timestamp when the classify job was last updated.",+ "project_id": "Identifier of the LlamaCloud project the job belongs to.",+ "user_id": "Identifier of the user who created the job.",+ "status": "Job status: PENDING, RUNNING, COMPLETED, or FAILED.",+ "error_message": "Error details when the job failed.",+ "file_input": "Identifier or reference of the classified input file.",+ "document_input_type": "How the input document was supplied (e.g. file id or URL).",+ "configuration_id": "Identifier of the classification configuration used.",+ "parse_job_id": "Identifier of the parse job that preprocessed the document, when applicable.",+ },+ },+ "batches": {+ "description": "Batch processing runs that apply parsing or extraction across a directory of files.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/batches",+ "columns": {+ "id": "Unique identifier for the batch.",+ "created_at": "Timestamp when the batch was created.",+ "updated_at": "Timestamp when the batch was last updated.",+ "project_id": "Identifier of the LlamaCloud project the batch belongs to.",+ "source_directory_id": "Identifier of the directory of files the batch processes.",+ "status": "Batch status: PENDING, THROTTLED, RUNNING, COMPLETED, FAILED, or CANCELLED.",+ "config": "Configuration the batch ran with.",+ "results": "Per-file results of the batch run.",+ },+ },+ "split_jobs": {+ "description": "Document splitting jobs that segment a document into categorized sub-documents.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/splitter",+ "columns": {+ "id": "Unique identifier for the split job.",+ "created_at": "Timestamp when the split job was created.",+ "updated_at": "Timestamp when the split job was last updated.",+ "project_id": "Identifier of the LlamaCloud project the job belongs to.",+ "user_id": "Identifier of the user who created the job.",+ "status": "Job status: pending, processing, completed, failed, or cancelled.",+ "error_message": "Error details when the job failed.",+ "file_input": "Identifier or reference of the input file the job split.",+ "categories": "Categories the job splits the document into.",+ "splitting_strategy": "Strategy used to split the document.",+ },+ },+ "sheets_jobs": {+ "description": "Spreadsheet parsing jobs (LlamaSheets), one row per spreadsheet job with per-region results metadata.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/sheets",+ "columns": {+ "id": "Unique identifier for the spreadsheet job.",+ "created_at": "Timestamp when the spreadsheet job was created.",+ "updated_at": "Timestamp when the spreadsheet job was last updated.",+ "project_id": "Identifier of the LlamaCloud project the job belongs to.",+ "user_id": "Identifier of the user who created the job.",+ "status": "Job status: PENDING, SUCCESS, ERROR, PARTIAL_SUCCESS, or CANCELLED.",+ "success": "Whether the job completed successfully.",+ "file_id": "Identifier of the spreadsheet file the job parsed.",+ "regions": "Table regions detected in the spreadsheet.",+ "worksheet_metadata": "Per-worksheet metadata for the parsed spreadsheet.",+ "errors": "Errors encountered while parsing the spreadsheet.",+ },+ },+ "projects": {+ "description": "LlamaCloud projects visible to the API key.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "created_at": "Timestamp when the project was created.",+ "updated_at": "Timestamp when the project was last updated.",+ "name": "Name of the project.",+ "organization_id": "Identifier of the organization the project belongs to.",+ "is_default": "Whether this is the organization's default project.",+ },+ },+ "pipelines": {+ "description": "Managed index pipelines that ingest, chunk, embed, and index documents for retrieval.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/pipelines",+ "columns": {+ "id": "Unique identifier for the pipeline.",+ "created_at": "Timestamp when the pipeline was created.",+ "updated_at": "Timestamp when the pipeline was last updated.",+ "name": "Name of the pipeline.",+ "project_id": "Identifier of the LlamaCloud project the pipeline belongs to.",+ "pipeline_type": "Type of the pipeline (e.g. MANAGED or PLAYGROUND).",+ },+ },+ "files": {+ "description": "Files uploaded to LlamaCloud for parsing, extraction, or indexing.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/files",+ "columns": {+ "id": "Unique identifier for the file.",+ "name": "Name of the file.",+ "external_file_id": "Caller-supplied external identifier for the file.",+ "file_type": "Type (extension) of the file.",+ "project_id": "Identifier of the LlamaCloud project the file belongs to.",+ "last_modified_at": "Timestamp when the file was last modified.",+ "expires_at": "Timestamp when the file expires, when set.",+ "purpose": "Purpose the file was uploaded for.",+ },+ },+ "usage_metrics": {+ "description": "Per-day usage aggregates with credit consumption across LlamaCloud products.",+ "docs_url": "https://developers.llamaindex.ai/python/cloud/api_reference/usage-metrics",+ "columns": {+ "id": "Unique identifier for the usage metric row.",+ "day": "Date (YYYY-MM-DD) the usage was recorded for.",+ "event_type": "Type of usage event the row aggregates.",+ "value": "Aggregated usage count for the day.",+ "credits": "Credits consumed by this usage.",+ "project_id": "Identifier of the LlamaCloud project the usage belongs to.",+ "organization_id": "Identifier of the organization the usage belongs to.",+ "user_id": "Identifier of the user who generated the usage.",+ "event_aggregation_type": "How the usage events were aggregated.",+ "event_aggregation_key": "Key the usage events were aggregated by.",+ "usage_tags": "Tags attached to the usage events.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.pynew file mode 100644index 000000000000..c3f15bc0e3c2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.py@@ -0,0 +1,251 @@+import dataclasses+from collections.abc import Iterator+from datetime import 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.datetime_utils import (+ coerce_datetime_to_utc,+)+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.llama_cloud.settings import (+ DEFAULT_LLAMA_CLOUD_REGION,+ LLAMA_CLOUD_ENDPOINTS,+ LLAMA_CLOUD_REGIONS,+ LlamaCloudEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+++class LlamaCloudRetryableError(Exception):+ pass+++def _project_rows(rows: list[dict[str, Any]], allowed_fields: frozenset[str]) -> list[dict[str, Any]]:+ """Keep only allowlisted top-level keys on each row.++ LlamaCloud pipeline definitions embed third-party credentials — embedding-provider+ API keys, data-sink connection secrets, bearer tokens — in nested config objects.+ Projecting onto the documented, non-sensitive fields keeps those secrets out of the+ warehouse structurally, rather than trying to enumerate every secret-bearing key.+ """+ return [{key: value for key, value in row.items() if key in allowed_fields} for row in rows]+++class LlamaCloudResumeConfig:+ next_page_token: str+++def get_base_url(region: str | None) -> str:+ normalized_region = (region or DEFAULT_LLAMA_CLOUD_REGION).lower()+ if normalized_region not in LLAMA_CLOUD_REGIONS:+ raise ValueError(f"LlamaCloud region must be one of {', '.join(sorted(LLAMA_CLOUD_REGIONS))}")+ return LLAMA_CLOUD_REGIONS[normalized_region]+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def _format_datetime(value: Any) -> str:+ """Format the incremental watermark for `created_at_on_or_after`.++ Truncates to whole seconds, rounding the inclusive lower bound *down* — a sync+ re-fetches at most a few boundary rows (merge dedupes them) rather than skipping any.+ """+ normalized_value = coerce_datetime_to_utc(value)+ if normalized_value is None:+ return str(value)+ return normalized_value.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _format_day(value: Any) -> str:+ """Format the incremental watermark for `day_on_or_after` (a plain YYYY-MM-DD date)."""+ if isinstance(value, datetime):+ return value.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ return str(value)+++def _format_incremental_value(config: LlamaCloudEndpointConfig, value: Any) -> str:+ if config.incremental_param == "day_on_or_after":+ return _format_day(value)+ return _format_datetime(value)+++@retry(+ retry=retry_if_exception_type(+ (+ LlamaCloudRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], params: dict[str, Any]) -> Any:+ # The tracked session's urllib3 retry already backs off on 429/5xx honoring Retry-After;+ # this tenacity layer catches what slips through once those retries are exhausted.+ response = session.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise LlamaCloudRetryableError(f"LlamaCloud API error (retryable): status={response.status_code}, url={url}")++ response.raise_for_status()++ return response.json()+++def _parse_error_detail(response: requests.Response) -> str:+ try:+ payload = response.json()+ if isinstance(payload, dict):+ detail = payload.get("detail")+ if isinstance(detail, str) and detail:+ return detail+ except Exception:+ pass+ return response.text+++def validate_credentials(api_key: str, region: str | None = None) -> tuple[bool, str | None]:+ try:+ base_url = get_base_url(region)+ except ValueError as exc:+ return False, str(exc)++ try:+ response = make_tracked_session().get(+ f"{base_url}/api/v2/projects",+ headers=_headers(api_key),+ params={"page_size": 1},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except requests.RequestException as exc:+ return False, f"Could not reach the LlamaCloud API: {exc}"++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ # LlamaCloud keys are project-scoped with no finer-grained scopes, and its 401 body+ # already points at the most common cause (a key from the other region).+ return False, f"Invalid LlamaCloud API key: {_parse_error_detail(response)}"+ return False, f"LlamaCloud API returned an unexpected error: {_parse_error_detail(response)}"+++def _resolve_organization_id(session: requests.Session, base_url: str, headers: dict[str, str]) -> str:+ """Resolve the organization id the usage-metrics endpoint requires.++ The API key is project-scoped, so the projects it can list all belong to the key's+ organization — the first project's organization_id is the right one.+ """+ data = _fetch_page(session, f"{base_url}/api/v2/projects", headers, {"page_size": 1})+ items = data.get("items") or []+ organization_id = items[0].get("organization_id") if items else None+ if not organization_id:+ raise ValueError("Could not resolve the LlamaCloud organization id from the API key's project")+ return organization_id+++def get_rows(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LlamaCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = LLAMA_CLOUD_ENDPOINTS[endpoint]+ base_url = get_base_url(region)+ url = f"{base_url}{config.path}"+ headers = _headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive.+ # Endpoints whose raw responses carry secrets opt out of HTTP sample capture — the+ # sampler observes the upstream body before row projection runs.+ session = make_tracked_session(capture=config.capture_http_samples)++ if not config.paginated:+ data = _fetch_page(session, url, headers, {})+ if data:+ yield _project_rows(data, config.output_fields) if config.output_fields else data+ return++ params: dict[str, Any] = {"page_size": config.page_size}++ if config.requires_organization_id:+ params["organization_id"] = _resolve_organization_id(session, base_url, headers)++ # Every endpoint advertises at most one incremental field, so the endpoint's filter+ # param maps directly to the user's chosen cursor field.+ if should_use_incremental_field and config.incremental_param and db_incremental_field_last_value is not None:+ params[config.incremental_param] = _format_incremental_value(config, db_incremental_field_last_value)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.next_page_token:+ params["page_token"] = resume_config.next_page_token+ logger.debug(f"LlamaCloud: resuming {endpoint} from page_token={resume_config.next_page_token}")++ while True:+ data = _fetch_page(session, url, headers, params)++ items = data.get("items") or []+ next_page_token = data.get("next_page_token")++ if items:+ yield _project_rows(items, config.output_fields) if config.output_fields else items++ if not next_page_token:+ break++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes the re-yielded rows on the primary key.+ resumable_source_manager.save_state(LlamaCloudResumeConfig(next_page_token=next_page_token))+ params["page_token"] = next_page_token+++def llama_cloud_source(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LlamaCloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = LLAMA_CLOUD_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ 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,+ ),+ primary_keys=config.primary_keys,+ # The list endpoints accept no sort param and don't document their ordering, so we+ # can't guarantee ascending rows. "desc" makes the pipeline persist the incremental+ # watermark (the max value seen) only after the sync completes, which is correct+ # regardless of the actual server order; page_token resume covers interruptions.+ sort_mode="desc" if config.incremental_param else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.pynew file mode 100644index 000000000000..e6c5b1c3e879--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.py@@ -0,0 +1,204 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# LlamaCloud API keys are region-specific: a key minted in one region only works+# against that region's host (https://developers.llamaindex.ai/python/cloud/general/regions).+LLAMA_CLOUD_REGIONS: dict[str, str] = {+ "na": "https://api.cloud.llamaindex.ai",+ "eu": "https://api.cloud.eu.llamaindex.ai",+}+DEFAULT_LLAMA_CLOUD_REGION = "na"++# The classify listing caps page_size at 100; the other cursor endpoints don't document a+# maximum, so 100 is safe everywhere.+DEFAULT_PAGE_SIZE = 100++# Jobs commonly transition status (PENDING -> COMPLETED/FAILED) shortly after creation, but+# the API only filters on created_at — so each incremental run re-reads a trailing day of+# rows to pick up those transitions; merge dedupes them on the primary key.+JOB_STATUS_LOOKBACK_SECONDS = 24 * 60 * 60++CREATED_AT_INCREMENTAL: IncrementalField = {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+}++DAY_INCREMENTAL: IncrementalField = {+ "label": "day",+ "type": IncrementalFieldType.Date,+ "field": "day",+ "field_type": IncrementalFieldType.Date,+}++JOB_ENDPOINT_DESCRIPTION = (+ "Incremental syncs filter on created_at, re-reading a trailing 24h window so recent status "+ "transitions are picked up; status changes to jobs created earlier than that are only "+ "reflected on a full refresh"+)+++@dataclass+class LlamaCloudEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Server-side inclusive lower-bound query param backing incremental syncs+ # (None -> the endpoint has no timestamp filter, full refresh only).+ incremental_param: str | None = None+ partition_key: str | None = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ page_size: int = DEFAULT_PAGE_SIZE+ # False for endpoints that return a bare JSON array with no page_token support.+ paginated: bool = True+ # /api/v1/beta/usage-metrics requires organization_id; it's resolved at sync time+ # from the key's project (see _resolve_organization_id).+ requires_organization_id: bool = False+ description: str | None = None+ default_incremental_lookback_seconds: int | None = None+ # Allowlist of top-level fields to keep per row. Set for config-style endpoints whose+ # payloads embed third-party credentials in nested config objects — projecting onto the+ # documented, non-sensitive fields keeps secrets out of the warehouse. None imports every field.+ output_fields: frozenset[str] | None = None+ # Whether raw HTTP responses may be captured as anonymized samples. Fail-closed: job and+ # config endpoints can carry customer document content (e.g. `user_metadata`,+ # `extract_result`) or embedded credentials that the name-based sample scrubbers can't+ # catch, so capture is opt-in and only enabled for endpoints whose response schema is+ # limited to safe metadata.+ capture_http_samples: bool = False+++LLAMA_CLOUD_ENDPOINTS: dict[str, LlamaCloudEndpointConfig] = {+ "parse_jobs": LlamaCloudEndpointConfig(+ name="parse_jobs",+ path="/api/v2/parse",+ incremental_fields=[CREATED_AT_INCREMENTAL],+ incremental_param="created_at_on_or_after",+ partition_key="created_at",+ description=JOB_ENDPOINT_DESCRIPTION,+ default_incremental_lookback_seconds=JOB_STATUS_LOOKBACK_SECONDS,+ ),+ "extract_jobs": LlamaCloudEndpointConfig(+ name="extract_jobs",+ path="/api/v2/extract",+ incremental_fields=[CREATED_AT_INCREMENTAL],+ incremental_param="created_at_on_or_after",+ partition_key="created_at",+ description=JOB_ENDPOINT_DESCRIPTION,+ default_incremental_lookback_seconds=JOB_STATUS_LOOKBACK_SECONDS,+ ),+ "classify_jobs": LlamaCloudEndpointConfig(+ name="classify_jobs",+ path="/api/v2/classify",+ incremental_fields=[CREATED_AT_INCREMENTAL],+ incremental_param="created_at_on_or_after",+ partition_key="created_at",+ description=JOB_ENDPOINT_DESCRIPTION,+ default_incremental_lookback_seconds=JOB_STATUS_LOOKBACK_SECONDS,+ ),+ "batches": LlamaCloudEndpointConfig(+ name="batches",+ path="/api/v2/batches",+ incremental_fields=[CREATED_AT_INCREMENTAL],+ incremental_param="created_at_on_or_after",+ partition_key="created_at",+ description=JOB_ENDPOINT_DESCRIPTION,+ default_incremental_lookback_seconds=JOB_STATUS_LOOKBACK_SECONDS,+ ),+ "split_jobs": LlamaCloudEndpointConfig(+ name="split_jobs",+ path="/api/v1/split/jobs",+ incremental_fields=[CREATED_AT_INCREMENTAL],+ incremental_param="created_at_on_or_after",+ partition_key="created_at",+ description=JOB_ENDPOINT_DESCRIPTION,+ default_incremental_lookback_seconds=JOB_STATUS_LOOKBACK_SECONDS,+ ),+ "sheets_jobs": LlamaCloudEndpointConfig(+ name="sheets_jobs",+ path="/api/v1/sheets/jobs",+ incremental_fields=[CREATED_AT_INCREMENTAL],+ incremental_param="created_at_on_or_after",+ partition_key="created_at",+ description=JOB_ENDPOINT_DESCRIPTION,+ default_incremental_lookback_seconds=JOB_STATUS_LOOKBACK_SECONDS,+ # Sheets jobs embed webhook credentials (signing secrets, auth headers) under nested+ # `parameters.webhook_configurations`, so import only the documented job metadata+ # (matches canonical_descriptions). Sampling stays off (the fail-closed default).+ output_fields=frozenset(+ {+ "id",+ "created_at",+ "updated_at",+ "project_id",+ "user_id",+ "status",+ "success",+ "file_id",+ "regions",+ "worksheet_metadata",+ "errors",+ }+ ),+ ),+ "projects": LlamaCloudEndpointConfig(+ name="projects",+ path="/api/v2/projects",+ # The projects listing has no timestamp filter, so full refresh only.+ # Response is limited to project metadata (no customer content or credentials), so+ # HTTP sample capture is safe to enable.+ capture_http_samples=True,+ ),+ "pipelines": LlamaCloudEndpointConfig(+ name="pipelines",+ path="/api/v1/pipelines",+ # Returns a bare JSON array with neither pagination nor timestamp filters.+ paginated=False,+ # Pipeline definitions embed nested embedding-provider and data-sink credentials, so+ # import only the documented metadata (matches canonical_descriptions). Sampling stays+ # off (the fail-closed default).+ output_fields=frozenset({"id", "created_at", "updated_at", "name", "project_id", "pipeline_type"}),+ ),+ "files": LlamaCloudEndpointConfig(+ name="files",+ path="/api/v1/beta/files",+ # The files listing has no timestamp filter (last_modified_at is not filterable),+ # so full refresh only.+ # Each file row carries a presigned `download_url` (and form fields) granting access to+ # the private source document, so import only the documented metadata (matches+ # canonical_descriptions). Sampling stays off (the fail-closed default).+ output_fields=frozenset(+ {+ "id",+ "name",+ "external_file_id",+ "file_type",+ "project_id",+ "last_modified_at",+ "expires_at",+ "purpose",+ }+ ),+ ),+ "usage_metrics": LlamaCloudEndpointConfig(+ name="usage_metrics",+ path="/api/v1/beta/usage-metrics",+ incremental_fields=[DAY_INCREMENTAL],+ incremental_param="day_on_or_after",+ requires_organization_id=True,+ # `day_on_or_after` is inclusive, so the boundary day is re-read each run and its+ # still-accumulating totals are updated via merge on the primary key.+ description="Per-day usage and credit consumption aggregates",+ # Response is limited to per-day usage aggregates (no customer content or credentials),+ # so HTTP sample capture is safe to enable.+ capture_http_samples=True,+ ),+}++ENDPOINTS = tuple(LLAMA_CLOUD_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LLAMA_CLOUD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.pyindex 7446489dfe0e..418f4e4f7b90 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/source.py@@ -1,19 +1,45 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LlamaCloudSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.llama_cloud import (+ LlamaCloudResumeConfig,+ llama_cloud_source,+ validate_credentials as validate_llama_cloud_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.settings import (+ DEFAULT_LLAMA_CLOUD_REGION,+ ENDPOINTS,+ LLAMA_CLOUD_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LlamaCloudSource(SimpleSource[LlamaCloudSourceConfig]):+class LlamaCloudSource(ResumableSource[LlamaCloudSourceConfig, LlamaCloudResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LLAMACLOUD@@ -24,8 +50,103 @@ class LlamaCloudSource(SimpleSource[LlamaCloudSourceConfig]):name=SchemaExternalDataSourceType.LLAMA_CLOUD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="LlamaCloud",- iconPath="/static/services/llama_cloud.png",+ docsUrl="https://posthog.com/docs/cdp/sources/llama-cloud",+ iconPath="/static/services/llama_cloud.svg",keywords=["llamaindex", "llamaparse", "document parsing", "rag"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption="""Enter a LlamaCloud API key to sync your parsing, extraction, and classification jobs, pipelines, projects, files, and usage metrics.++You can create an API key in [LlamaCloud](https://cloud.llamaindex.ai) under **Settings → API Keys**. API keys are project-scoped and region-specific, so pick the region your key was created in.+""",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="llx-...",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue=DEFAULT_LLAMA_CLOUD_REGION,+ options=[+ SourceFieldSelectConfigOption(label="North America (api.cloud.llamaindex.ai)", value="na"),+ SourceFieldSelectConfigOption(label="Europe (api.cloud.eu.llamaindex.ai)", value="eu"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Both regional hosts share the https://api.cloud. prefix, so one key per status+ # covers NA and EU without matching unrelated hosts.+ return {+ "401 Client Error: Unauthorized for url: https://api.cloud.": "Your LlamaCloud API key is invalid, revoked, or from a different region. Create a new API key in LlamaCloud, check the region, and reconnect.",+ "403 Client Error: Forbidden for url: https://api.cloud.": "Your LlamaCloud API key does not have access to this data. Check the key's project in LlamaCloud and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: LlamaCloudSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas: list[SourceSchema] = []+ for endpoint in ENDPOINTS:+ if names and endpoint not in names:+ continue++ endpoint_config = LLAMA_CLOUD_ENDPOINTS[endpoint]+ supports_incremental = endpoint_config.incremental_param is not None+ schemas.append(+ SourceSchema(+ name=endpoint,+ supports_incremental=supports_incremental,+ supports_append=supports_incremental,+ incremental_fields=endpoint_config.incremental_fields,+ description=endpoint_config.description,+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,+ )+ )+ return schemas++ def validate_credentials(+ self, config: LlamaCloudSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_llama_cloud_credentials(api_key=config.api_key, region=config.region)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LlamaCloudResumeConfig]:+ return ResumableSourceManager[LlamaCloudResumeConfig](inputs, LlamaCloudResumeConfig)++ def source_for_pipeline(+ self,+ config: LlamaCloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[LlamaCloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return llama_cloud_source(+ api_key=config.api_key,+ region=config.region,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud.pynew file mode 100644index 000000000000..df7b8c96bedb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud.py@@ -0,0 +1,453 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.llama_cloud import (+ LlamaCloudResumeConfig,+ LlamaCloudRetryableError,+ _fetch_page,+ _format_datetime,+ _format_day,+ get_base_url,+ get_rows,+ llama_cloud_source,+ validate_credentials,+)++TRANSPORT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.llama_cloud"++# tenacity exposes the undecorated function via `__wrapped__`, so status classification can be+# tested without sitting through the retry backoff.+_fetch_page_once = _fetch_page.__wrapped__ # type: ignore[attr-defined]+++class FakeSession:+ """Records each GET's url and a snapshot of its params, returning canned payloads.++ Params must be snapshotted because the transport mutates one params dict across pages.+ """++ def __init__(self, payloads: list[Any]) -> None:+ self._payloads = list(payloads)+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def get(self, url: str, headers: dict[str, str], params: dict[str, Any], timeout: int) -> MagicMock:+ self.calls.append((url, dict(params)))+ response = MagicMock()+ response.status_code = 200+ response.json.return_value = self._payloads.pop(0)+ response.raise_for_status.return_value = None+ return response+++def _make_manager(resume_state: Optional[LlamaCloudResumeConfig] = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _page(items: list[dict[str, Any]], next_page_token: str | None = None) -> dict[str, Any]:+ return {"items": items, "next_page_token": next_page_token, "total_size": len(items)}+++class TestLlamaCloudTransport:+ @parameterized.expand(+ [+ (None, "https://api.cloud.llamaindex.ai"),+ ("na", "https://api.cloud.llamaindex.ai"),+ ("eu", "https://api.cloud.eu.llamaindex.ai"),+ ("EU", "https://api.cloud.eu.llamaindex.ai"),+ ]+ )+ def test_get_base_url(self, region: str | None, expected: str) -> None:+ assert get_base_url(region) == expected++ def test_get_base_url_rejects_unknown_region(self) -> None:+ with pytest.raises(ValueError, match="region must be one of"):+ get_base_url("apac")++ @parameterized.expand(+ [+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 123456), "2026-03-01T12:30:45Z"),+ ("aware_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "2026-03-01T12:30:45Z"),+ ("passthrough_string", "2026-03-01T12:30:45Z", "2026-03-01T12:30:45Z"),+ ]+ )+ def test_format_datetime(self, _name: str, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected++ @parameterized.expand(+ [+ ("date", date(2026, 3, 1), "2026-03-01"),+ ("datetime", datetime(2026, 3, 1, 12, 30, 45), "2026-03-01"),+ ("passthrough_string", "2026-03-01", "2026-03-01"),+ ]+ )+ def test_format_day(self, _name: str, value: Any, expected: str) -> None:+ assert _format_day(value) == expected++ def test_get_rows_paginates_with_page_token(self) -> None:+ session = FakeSession(+ [+ _page([{"id": "job-1"}], next_page_token="token-1"),+ _page([{"id": "job-2"}], next_page_token=None),+ ]+ )+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "na", "parse_jobs", MagicMock(), manager))++ assert batches == [[{"id": "job-1"}], [{"id": "job-2"}]]+ assert session.calls[0][0] == "https://api.cloud.llamaindex.ai/api/v2/parse"+ assert "page_token" not in session.calls[0][1]+ assert session.calls[1][1]["page_token"] == "token-1"+ assert session.calls[0][1]["page_size"] == 100++ def test_get_rows_saves_resume_state_after_yield(self) -> None:+ session = FakeSession(+ [+ _page([{"id": "job-1"}], next_page_token="token-1"),+ _page([{"id": "job-2"}], next_page_token=None),+ ]+ )+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ rows = get_rows("llx-test", "na", "parse_jobs", MagicMock(), manager)+ next(rows)+ # Suspended at the first yield: a crash here must re-yield this page on retry,+ # so the resume state can't have been persisted yet.+ manager.save_state.assert_not_called()+ next(rows)++ manager.save_state.assert_called_once_with(LlamaCloudResumeConfig(next_page_token="token-1"))++ def test_get_rows_resumes_from_saved_page_token(self) -> None:+ session = FakeSession([_page([{"id": "job-3"}], next_page_token=None)])+ manager = _make_manager(resume_state=LlamaCloudResumeConfig(next_page_token="token-2"))++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "na", "parse_jobs", MagicMock(), manager))++ assert batches == [[{"id": "job-3"}]]+ assert session.calls[0][1]["page_token"] == "token-2"++ def test_get_rows_incremental_sends_created_at_filter(self) -> None:+ session = FakeSession([_page([], next_page_token=None)])+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ list(+ get_rows(+ "llx-test",+ "na",+ "parse_jobs",+ MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ )++ assert session.calls[0][1]["created_at_on_or_after"] == "2026-01-02T03:04:05Z"++ def test_get_rows_full_refresh_omits_incremental_filter(self) -> None:+ session = FakeSession([_page([{"id": "job-1"}], next_page_token=None)])+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ list(get_rows("llx-test", "na", "parse_jobs", MagicMock(), manager))++ assert "created_at_on_or_after" not in session.calls[0][1]++ def test_get_rows_usage_metrics_resolves_organization_id(self) -> None:+ session = FakeSession(+ [+ _page([{"id": "project-1", "organization_id": "org-1"}]),+ _page([{"id": "metric-1", "day": "2026-01-01"}], next_page_token=None),+ ]+ )+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ "llx-test",+ "na",+ "usage_metrics",+ MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 1),+ )+ )++ assert batches == [[{"id": "metric-1", "day": "2026-01-01"}]]+ assert session.calls[0][0] == "https://api.cloud.llamaindex.ai/api/v2/projects"+ metrics_url, metrics_params = session.calls[1]+ assert metrics_url == "https://api.cloud.llamaindex.ai/api/v1/beta/usage-metrics"+ assert metrics_params["organization_id"] == "org-1"+ assert metrics_params["day_on_or_after"] == "2026-01-01"++ def test_get_rows_usage_metrics_fails_without_resolvable_organization(self) -> None:+ session = FakeSession([_page([])])+ manager = _make_manager()++ with (+ patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session),+ pytest.raises(ValueError, match="organization id"),+ ):+ list(get_rows("llx-test", "na", "usage_metrics", MagicMock(), manager))++ def test_get_rows_pipelines_yields_bare_array_without_pagination(self) -> None:+ session = FakeSession([[{"id": "pipeline-1"}, {"id": "pipeline-2"}]])+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "eu", "pipelines", MagicMock(), manager))++ assert batches == [[{"id": "pipeline-1"}, {"id": "pipeline-2"}]]+ url, params = session.calls[0]+ assert url == "https://api.cloud.eu.llamaindex.ai/api/v1/pipelines"+ assert params == {}++ def test_get_rows_pipelines_projects_to_documented_fields(self) -> None:+ # Pipeline definitions embed third-party credentials in nested config; only the+ # documented, non-sensitive metadata reaches the warehouse. Includes token/credentials/+ # headers — the generically-named secrets a key-name denylist would let through.+ session = FakeSession(+ [+ [+ {+ "id": "pipeline-1",+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-02T00:00:00Z",+ "name": "docs",+ "project_id": "proj-1",+ "pipeline_type": "MANAGED",+ "embedding_config": {"component": {"api_key": "sk-secret"}},+ "data_sink": {+ "component": {+ "token": "bearer-secret",+ "credentials": {"password": "hunter2"},+ "headers": {"Authorization": "Bearer x"},+ }+ },+ }+ ]+ ]+ )+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "eu", "pipelines", MagicMock(), manager))++ assert batches == [+ [+ {+ "id": "pipeline-1",+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-02T00:00:00Z",+ "name": "docs",+ "project_id": "proj-1",+ "pipeline_type": "MANAGED",+ }+ ]+ ]++ def test_get_rows_sheets_jobs_projects_to_documented_fields(self) -> None:+ # Sheets jobs embed webhook credentials under nested `parameters.webhook_configurations`;+ # only the documented job metadata reaches the warehouse. Exercises the paginated+ # projection path (distinct from the bare-array pipelines endpoint).+ session = FakeSession(+ [+ _page(+ [+ {+ "id": "sheet-1",+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-02T00:00:00Z",+ "project_id": "proj-1",+ "user_id": "user-1",+ "status": "SUCCESS",+ "success": True,+ "file_id": "file-1",+ "regions": [],+ "worksheet_metadata": {},+ "errors": [],+ "parameters": {+ "webhook_configurations": [+ {+ "webhook_signing_secret": "whsec-secret",+ "webhook_headers": {"Authorization": "Bearer x"},+ }+ ]+ },+ }+ ],+ next_page_token=None,+ )+ ]+ )+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "eu", "sheets_jobs", MagicMock(), manager))++ assert batches == [+ [+ {+ "id": "sheet-1",+ "created_at": "2026-01-01T00:00:00Z",+ "updated_at": "2026-01-02T00:00:00Z",+ "project_id": "proj-1",+ "user_id": "user-1",+ "status": "SUCCESS",+ "success": True,+ "file_id": "file-1",+ "regions": [],+ "worksheet_metadata": {},+ "errors": [],+ }+ ]+ ]++ def test_get_rows_files_projects_to_documented_fields(self) -> None:+ # Each file row carries a presigned `download_url` (and form fields) granting access to+ # the private source document; only the documented metadata reaches the warehouse.+ session = FakeSession(+ [+ _page(+ [+ {+ "id": "file-1",+ "name": "invoice.pdf",+ "external_file_id": "ext-1",+ "file_type": "pdf",+ "project_id": "proj-1",+ "last_modified_at": "2026-01-02T00:00:00Z",+ "expires_at": "2026-02-01T00:00:00Z",+ "purpose": "parse",+ "download_url": "https://s3.example.com/private?X-Amz-Signature=secret",+ "download_form_fields": {"key": "value", "policy": "secret"},+ }+ ],+ next_page_token=None,+ )+ ]+ )+ manager = _make_manager()++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("llx-test", "eu", "files", MagicMock(), manager))++ assert batches == [+ [+ {+ "id": "file-1",+ "name": "invoice.pdf",+ "external_file_id": "ext-1",+ "file_type": "pdf",+ "project_id": "proj-1",+ "last_modified_at": "2026-01-02T00:00:00Z",+ "expires_at": "2026-02-01T00:00:00Z",+ "purpose": "parse",+ }+ ]+ ]++ @parameterized.expand([(429,), (500,), (503,)])+ def test_fetch_page_raises_retryable_error(self, status_code: int) -> None:+ session = MagicMock()+ response = MagicMock(status_code=status_code)+ session.get.return_value = response++ with pytest.raises(LlamaCloudRetryableError):+ _fetch_page_once(session, "https://api.cloud.llamaindex.ai/api/v2/parse", {}, {})++ def test_fetch_page_raises_http_error_for_client_errors(self) -> None:+ session = MagicMock()+ response = MagicMock(status_code=401)+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ _fetch_page_once(session, "https://api.cloud.llamaindex.ai/api/v2/parse", {}, {})++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid LlamaCloud API key: Invalid API Key. Please check your region"),+ (500, False, "LlamaCloud API returned an unexpected error"),+ ]+ )+ @patch(f"{TRANSPORT_MODULE}.make_tracked_session")+ def test_validate_credentials_status_mapping(+ self, status_code: int, expected_valid: bool, expected_message: str | None, mock_session: MagicMock+ ) -> None:+ response = MagicMock(status_code=status_code)+ response.json.return_value = {"detail": "Invalid API Key. Please check your region"}+ mock_session.return_value.get.return_value = response++ is_valid, message = validate_credentials("llx-test", "na")++ assert is_valid is expected_valid+ if expected_message is None:+ assert message is None+ else:+ assert message is not None and expected_message in message++ @patch(f"{TRANSPORT_MODULE}.make_tracked_session")+ def test_validate_credentials_handles_connection_error(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")++ is_valid, message = validate_credentials("llx-test", "na")++ assert is_valid is False+ assert message is not None and "Could not reach the LlamaCloud API" in message++ def test_validate_credentials_rejects_unknown_region(self) -> None:+ is_valid, message = validate_credentials("llx-test", "apac")+ assert is_valid is False+ assert message is not None and "region must be one of" in message++ @patch(f"{TRANSPORT_MODULE}.make_tracked_session")+ def test_validate_credentials_falls_back_to_response_text_on_non_json_body(self, mock_session: MagicMock) -> None:+ # A gateway can answer an error with an HTML/text body; parsing it as JSON must not crash.+ response = MagicMock(status_code=401)+ response.json.side_effect = ValueError("not json")+ response.text = "Bad Gateway"+ mock_session.return_value.get.return_value = response++ is_valid, message = validate_credentials("llx-test", "na")++ assert is_valid is False+ assert message is not None and "Bad Gateway" in message++ @parameterized.expand(+ [+ # No sort param exists on the API, so incremental endpoints report "desc" — the+ # watermark only persists once the sync completes.+ ("parse_jobs", "desc", ["created_at"]),+ ("usage_metrics", "desc", None),+ ("projects", "asc", None),+ ("pipelines", "asc", None),+ ]+ )+ def test_llama_cloud_source_response_shape(+ self, endpoint: str, expected_sort_mode: str, expected_partition_keys: list[str] | None+ ) -> None:+ response = llama_cloud_source("llx-test", "na", endpoint, MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == expected_sort_mode+ assert response.partition_keys == expected_partition_keys+ assert response.partition_mode == ("datetime" if expected_partition_keys else None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud_source.pynew file mode 100644index 000000000000..ef8da47694f3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/tests/test_llama_cloud_source.py@@ -0,0 +1,206 @@+from typing import Optional++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LlamaCloudSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.llama_cloud import (+ LlamaCloudResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.settings import (+ ENDPOINTS,+ LLAMA_CLOUD_ENDPOINTS,+ LlamaCloudEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.source import LlamaCloudSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(+ schema_name: str = "parse_jobs",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[str] = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="created_at" if should_use_incremental_field else None,+ incremental_field_type=None,+ job_id="job-id",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestLlamaCloudSource:+ def setup_method(self) -> None:+ self.source = LlamaCloudSource()+ self.team_id = 1+ self.config = LlamaCloudSourceConfig(api_key="llx-test")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.LLAMACLOUD++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "LlamaCloud"+ assert config.label == "LlamaCloud"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/llama_cloud.svg"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/llama-cloud"++ def test_source_config_fields(self) -> None:+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig))+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ region_field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))+ assert region_field.name == "region"+ assert region_field.defaultValue == "na"+ assert [option.value for option in region_field.options] == ["na", "eu"]++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("parse_jobs", True, "created_at"),+ ("extract_jobs", True, "created_at"),+ ("classify_jobs", True, "created_at"),+ ("batches", True, "created_at"),+ ("split_jobs", True, "created_at"),+ ("sheets_jobs", True, "created_at"),+ ("usage_metrics", True, "day"),+ # No server-side timestamp filter on these listings, so full refresh only.+ ("projects", False, None),+ ("pipelines", False, None),+ ("files", False, None),+ ]+ )+ def test_get_schemas_incremental_semantics(+ self, endpoint: str, supports_incremental: bool, incremental_field: str | None+ ) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is supports_incremental+ assert schema.supports_append is supports_incremental+ assert [f["field"] for f in schema.incremental_fields] == ([incremental_field] if incremental_field else [])++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["parse_jobs", "projects"])+ assert {s.name for s in schemas} == {"parse_jobs", "projects"}++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_job_schemas_declare_status_lookback(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["parse_jobs"].default_incremental_lookback_seconds == 24 * 60 * 60+ assert schemas["projects"].default_incremental_lookback_seconds is None++ def test_http_sample_capture_is_fail_closed(self) -> None:+ # A new endpoint config must default to no HTTP sample capture; only endpoints whose+ # response is limited to safe metadata opt in. Guards against a job/config endpoint+ # (which can carry customer document content or embedded credentials) silently+ # sampling raw responses into object storage.+ assert LlamaCloudEndpointConfig(name="x", path="/y").capture_http_samples is False+ capturing = {name for name, config in LLAMA_CLOUD_ENDPOINTS.items() if config.capture_http_samples}+ assert capturing == {"projects", "usage_metrics"}++ def test_documented_tables_render_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ parse_jobs = next(t for t in tables if t["name"] == "parse_jobs")+ assert parse_jobs["description"]++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.cloud.llamaindex.ai/api/v2/parse?page_size=100",),+ ("401 Client Error: Unauthorized for url: https://api.cloud.eu.llamaindex.ai/api/v2/projects",),+ ("403 Client Error: Forbidden for url: https://api.cloud.llamaindex.ai/api/v1/beta/files",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.cloud.llamaindex.ai/api/v2/parse",),+ ("401 Client Error: Unauthorized for url: https://api.example.com/api/v2/parse",),+ ]+ )+ def test_non_retryable_errors_ignore_unrelated(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.source.validate_llama_cloud_credentials"+ )+ def test_validate_credentials_passes_region(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)+ config = LlamaCloudSourceConfig(api_key="llx-test", region="eu")++ result = self.source.validate_credentials(config, self.team_id)++ assert result == (True, None)+ mock_validate.assert_called_once_with(api_key="llx-test", region="eu")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert manager._data_class is LlamaCloudResumeConfig++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.source.llama_cloud_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: MagicMock) -> None:+ inputs = _make_inputs(+ schema_name="extract_jobs",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )+ manager = MagicMock()+ config = LlamaCloudSourceConfig(api_key="llx-test", region="eu")++ self.source.source_for_pipeline(config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="llx-test",+ region="eu",+ endpoint="extract_jobs",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.llama_cloud.source.llama_cloud_source")+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_source: MagicMock) -> None:+ inputs = _make_inputs(+ schema_name="parse_jobs",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ self.source.source_for_pipeline(self.config, MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None