: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 skyvern import source (#70043)
Tom Owersea91c3a3fc21
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ada3a7bb0300..f983dca89c53 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -351,6 +351,7 @@ the row lists both.| shortio | HTTP | requests | ✅ || simplecast | HTTP | requests | ✅ || simplesat | HTTP | requests | ✅ |+| skyvern | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ || smaily | HTTP | requests | ✅ || smartreach | HTTP | requests | ✅ |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 9f2592a7da03..754358d5253e 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@@ -3442,7 +3442,8 @@ class SingularSourceConfig(config.Config):@config.configclass SkyvernSourceConfig(config.Config):- pass+ api_key: str+ base_url: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/canonical_descriptions.pynew file mode 100644index 000000000000..82155b88dbc0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/canonical_descriptions.py@@ -0,0 +1,110 @@+"""Canonical, documentation-sourced descriptions for Skyvern endpoints and columns.++Sourced from the official Skyvern API reference (https://docs.skyvern.com/api-reference). Keyed by the+endpoint names in `settings.py` `SKYVERN_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Skyvern table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "workflows": {+ "description": "A Skyvern workflow definition — a reusable, multi-step browser-automation agent.",+ "docs_url": "https://docs.skyvern.com/api-reference/api-reference/workflows",+ "columns": {+ "workflow_id": "Identifier of this specific workflow version.",+ "workflow_permanent_id": "Stable identifier that persists across all versions of the workflow.",+ "organization_id": "Identifier of the organization that owns the workflow.",+ "title": "Human-readable title of the workflow.",+ "description": "Description of what the workflow does.",+ "version": "Version number of this workflow definition.",+ "is_saved_task": "Whether this workflow was created from a saved task.",+ "is_template": "Whether this workflow is a reusable template.",+ "workflow_definition": "The full block/parameter definition of the workflow.",+ "status": "Publish status of the workflow (e.g. published, draft).",+ "proxy_location": "Geographic proxy location runs of this workflow use.",+ "webhook_callback_url": "URL Skyvern calls back when a run of this workflow completes.",+ "folder_id": "Identifier of the folder the workflow lives in, if any.",+ "created_at": "Time at which the workflow version was created.",+ "modified_at": "Time at which the workflow version was last modified.",+ "deleted_at": "Time at which the workflow was deleted, if it has been.",+ },+ },+ "runs": {+ "description": "A single run of a Skyvern task or workflow, with status, credits used, and timing.",+ "docs_url": "https://docs.skyvern.com/api-reference/api-reference/workflows/get-workflow-runs-by-id",+ "columns": {+ "workflow_run_id": "Unique identifier for the run.",+ "workflow_id": "Identifier of the workflow version that was run.",+ "workflow_permanent_id": "Stable identifier of the workflow that was run.",+ "organization_id": "Identifier of the organization that owns the run.",+ "workflow_title": "Title of the workflow that was run.",+ "status": "Current run status (created, queued, running, completed, failed, terminated, canceled, timed_out, paused).",+ "failure_reason": "Human-readable reason the run failed, if it did.",+ "failure_category": "Categorized failure information for the run.",+ "trigger_type": "What triggered the run (e.g. api, schedule, ui).",+ "workflow_schedule_id": "Identifier of the schedule that triggered the run, if any.",+ "credits_used": "Number of Skyvern credits the run consumed.",+ "cached_credits_used": "Number of credits served from cache for the run.",+ "browser_session_id": "Identifier of the browser session the run used.",+ "browser_profile_id": "Identifier of the browser profile the run used.",+ "parent_workflow_run_id": "Identifier of the parent run, for nested workflow runs.",+ "webhook_callback_url": "URL Skyvern called back when the run completed.",+ "queued_at": "Time at which the run was queued.",+ "started_at": "Time at which the run started executing.",+ "finished_at": "Time at which the run finished.",+ "created_at": "Time at which the run was created.",+ "modified_at": "Time at which the run was last modified.",+ },+ },+ "schedules": {+ "description": "A cron schedule that triggers a Skyvern workflow to run automatically.",+ "docs_url": "https://docs.skyvern.com/api-reference/api-reference/schedules",+ "columns": {+ "workflow_schedule_id": "Unique identifier for the schedule.",+ "organization_id": "Identifier of the organization that owns the schedule.",+ "workflow_permanent_id": "Stable identifier of the workflow the schedule triggers.",+ "workflow_title": "Title of the workflow the schedule triggers.",+ "cron_expression": "Cron expression defining when the schedule fires.",+ "timezone": "Timezone the cron expression is evaluated in.",+ "enabled": "Whether the schedule is currently active.",+ "parameters": "Parameter values passed to each scheduled run.",+ "name": "Name of the schedule.",+ "description": "Description of the schedule.",+ "next_run": "Time at which the schedule will next fire.",+ "created_at": "Time at which the schedule was created.",+ "modified_at": "Time at which the schedule was last modified.",+ },+ },+ "browser_profiles": {+ "description": "A persisted browser profile (cookies and local storage) reusable across runs.",+ "docs_url": "https://docs.skyvern.com/api-reference/api-reference/browser-profiles",+ "columns": {+ "browser_profile_id": "Unique identifier for the browser profile.",+ "organization_id": "Identifier of the organization that owns the profile.",+ "name": "Name of the browser profile.",+ "description": "Description of the browser profile.",+ "is_managed": "Whether the profile is managed by Skyvern.",+ "proxy_location": "Geographic proxy location the profile uses.",+ "workflow_permanent_id": "Stable identifier of the workflow the profile is tied to, if any.",+ "created_at": "Time at which the profile was created.",+ "modified_at": "Time at which the profile was last modified.",+ "deleted_at": "Time at which the profile was deleted, if it has been.",+ },+ },+ "credentials": {+ "description": "Metadata for a stored credential used by workflows. Secret values are never returned.",+ "docs_url": "https://docs.skyvern.com/api-reference/api-reference/credentials",+ "columns": {+ "credential_id": "Unique identifier for the credential.",+ "name": "Name of the credential.",+ "credential_type": "Type of credential (e.g. password, credit_card).",+ "vault_type": "The vault backing the credential.",+ "browser_profile_id": "Identifier of the browser profile the credential is tied to, if any.",+ "tested_url": "URL the credential was last tested against.",+ "folder_id": "Identifier of the folder the credential lives in, if any.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/settings.pynew file mode 100644index 000000000000..c42d2c29ccc9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/settings.py@@ -0,0 +1,101 @@+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class SkyvernEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField]+ # Some Skyvern list endpoints return a bare JSON array; others wrap the rows in an object+ # (e.g. /v1/schedules -> {"schedules": [...], "total_count": ...}). `data_key` names the wrapper+ # field when present, otherwise the response is treated as a bare array.+ data_key: Optional[str] = None+ # A STABLE creation timestamp used for datetime partitioning. Never a mutable field like+ # modified_at, whose partitions would rewrite on every sync.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ # Only true for endpoints exposing a genuine server-side timestamp filter (created_at_start).+ supports_incremental: bool = False+ default_incremental_field: Optional[str] = None+ # Safety overlap subtracted from the incremental watermark on every run. Skyvern run records+ # keep mutating (status, credits_used, finished_at) until they reach a terminal state, but the+ # only server-side filter is on the immutable created_at. Re-pulling a trailing window each run+ # lets merge pick up those late mutations for recently-created runs.+ incremental_lookback: Optional[timedelta] = None+ # Fan out over every workflow: enumerate workflows via /v1/agents, then pull each workflow's runs+ # from /v1/agents/{workflow_permanent_id}/runs (the only run endpoint with a created_at filter).+ fan_out_over_workflows: bool = False+ # Extra query params merged into every request for this endpoint.+ extra_params: dict[str, str] = field(default_factory=dict)+++_CREATED_AT_FIELD: IncrementalField = {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+}+++SKYVERN_ENDPOINTS: dict[str, SkyvernEndpointConfig] = {+ # Workflow definitions (latest version per workflow_permanent_id). /v1/agents has no server-side+ # timestamp filter, so this is full refresh only.+ "workflows": SkyvernEndpointConfig(+ name="workflows",+ path="/v1/agents",+ extra_params={"only_workflows": "true"},+ primary_keys=["workflow_permanent_id"],+ partition_key="created_at",+ incremental_fields=[],+ ),+ # Task/workflow run history. Fanned out per workflow because /v1/agents/{workflow_id}/runs is the+ # only run endpoint that accepts created_at_start (the global /v1/runs caps page<=100, ~10k newest+ # runs, and has no time filter). Incremental on the immutable created_at with a lookback window.+ "runs": SkyvernEndpointConfig(+ name="runs",+ path="/v1/agents/{workflow_permanent_id}/runs",+ primary_keys=["workflow_run_id"],+ partition_key="created_at",+ supports_incremental=True,+ default_incremental_field="created_at",+ incremental_lookback=timedelta(days=3),+ fan_out_over_workflows=True,+ incremental_fields=[_CREATED_AT_FIELD],+ ),+ # Scheduled workflow runs. Wrapped response. No server-side time filter -> full refresh.+ "schedules": SkyvernEndpointConfig(+ name="schedules",+ path="/v1/schedules",+ data_key="schedules",+ primary_keys=["workflow_schedule_id"],+ partition_key="created_at",+ incremental_fields=[],+ ),+ # Persisted browser profiles (cookies/local storage snapshots). No server-side time filter.+ "browser_profiles": SkyvernEndpointConfig(+ name="browser_profiles",+ path="/v1/browser_profiles",+ primary_keys=["browser_profile_id"],+ partition_key="created_at",+ incremental_fields=[],+ ),+ # Stored credential metadata (secret values are never returned by the API, only metadata).+ # CredentialResponse carries no timestamp, so there is no partition key and no incremental option.+ "credentials": SkyvernEndpointConfig(+ name="credentials",+ path="/v1/credentials",+ primary_keys=["credential_id"],+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(SKYVERN_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SKYVERN_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/skyvern.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/skyvern.pynew file mode 100644index 000000000000..14de14c06113--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/skyvern.py@@ -0,0 +1,342 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.settings import (+ SKYVERN_ENDPOINTS,+ SkyvernEndpointConfig,+)++SKYVERN_DEFAULT_BASE_URL = "https://api.skyvern.com"++# Every paginated list endpoint accepts page/page_size. 100 is the documented max for /v1/runs and a+# safe ceiling for the others (their only documented bound is a minimum of 1).+PAGE_SIZE = 100++# Bound per-workflow paging on incremental syncs so a huge run history can't scan unbounded. 100 pages+# * 100 rows = 10k runs per workflow within the created_at_start window. Full refreshes ignore this cap+# (see _get_fan_out_rows) so a workflow's older runs are never permanently truncated.+MAX_PAGES_PER_WORKFLOW = 100+++class SkyvernRetryableError(Exception):+ pass+++class SkyvernResumeConfig:+ # Next page number to fetch (1-based).+ page: int = 1+ # For the runs fan-out: the workflow currently being paged. A stable workflow_permanent_id+ # bookmark (not a positional index) so workflows added/removed between a crash and the retry can't+ # resume us into the wrong workflow. None for the standard (non-fan-out) endpoints.+ workflow_permanent_id: Optional[str] = None+++def _base_url(base_url: str | None) -> str:+ return (base_url or SKYVERN_DEFAULT_BASE_URL).rstrip("/")+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"x-api-key": api_key, "Accept": "application/json"}+++def _format_datetime_z(dt: datetime) -> str:+ """Format a datetime as ISO 8601 UTC, which Skyvern's created_at_start filter expects."""+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+++def _to_datetime(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str) and value:+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return None+++def _created_at_start(+ config: SkyvernEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str | None:+ """Build the created_at_start filter value from the incremental watermark.++ Subtracts the endpoint's lookback and clamps to now (a future-dated cursor would filter out every+ row). The re-pulled window is deduped by merge on the primary key.+ """+ if not (should_use_incremental_field and config.supports_incremental and db_incremental_field_last_value):+ return None+ dt = _to_datetime(db_incremental_field_last_value)+ if dt is None:+ return None+ if config.incremental_lookback:+ dt = dt - config.incremental_lookback+ now = datetime.now(UTC)+ aware = dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)+ if aware > now:+ dt = now+ return _format_datetime_z(dt)+++@retry(+ retry=retry_if_exception_type(+ (+ SkyvernRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, params: dict[str, Any], headers: dict[str, str], logger: FilteringBoundLogger+) -> Any:+ full_url = f"{url}?{urlencode(params)}" if params else url+ response = session.get(full_url, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise SkyvernRetryableError(f"Skyvern API error (retryable): status={response.status_code}, url={full_url}")++ if not response.ok:+ logger.error(f"Skyvern API error: status={response.status_code}, body={response.text}, url={full_url}")+ response.raise_for_status()++ return response.json()+++def _extract_items(data: Any, data_key: str | None) -> list[dict[str, Any]]:+ """A Skyvern list response is either a bare array or an object wrapping the rows under `data_key`."""+ if data_key is not None:+ if isinstance(data, dict):+ items = data.get(data_key) or []+ return items if isinstance(items, list) else []+ return []+ return data if isinstance(data, list) else []+++def validate_credentials(api_key: str, base_url: str | None) -> tuple[bool, str | None]:+ """Probe the cheapest list endpoint to confirm the API key is genuine."""+ url = f"{_base_url(base_url)}/v1/agents"+ try:+ # base_url is user-supplied, so treat it as an SSRF boundary: pin redirects off so a+ # malicious/self-hosted host can't bounce the API key to an internal address. The egress proxy+ # is the load-bearing control; this is defense-in-depth.+ response = make_tracked_session(allow_redirects=False).get(+ url, headers=_get_headers(api_key), params={"page": 1, "page_size": 1}, timeout=10+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Skyvern API key"+ return False, f"Skyvern API returned status {response.status_code}"+++def _iter_workflow_ids(+ session: requests.Session, base_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ """Page through /v1/agents (workflows only) and yield each workflow_permanent_id."""+ url = f"{base_url}/v1/agents"+ page = 1+ while True:+ data = _fetch_page(+ session, url, {"page": page, "page_size": PAGE_SIZE, "only_workflows": "true"}, headers, logger+ )+ items = _extract_items(data, None)+ if not items:+ break+ for item in items:+ wpid = item.get("workflow_permanent_id")+ if wpid:+ yield wpid+ if len(items) < PAGE_SIZE:+ break+ page += 1+++def _get_simple_rows(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SkyvernResumeConfig],+ config: SkyvernEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if (resume and resume.page) else 1+ url = f"{base_url}{config.path}"++ while True:+ params = {"page": page, "page_size": PAGE_SIZE, **config.extra_params}+ data = _fetch_page(session, url, params, headers, logger)+ items = _extract_items(data, config.data_key)+ if not items:+ break++ yield items++ if len(items) < PAGE_SIZE:+ break+ page += 1+ # Save AFTER yielding so a crash re-fetches the last page rather than skipping it; merge+ # dedupes on the primary key.+ resumable_source_manager.save_state(SkyvernResumeConfig(page=page))+++def _get_fan_out_rows(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SkyvernResumeConfig],+ config: SkyvernEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every workflow, pulling its runs from /v1/agents/{workflow_permanent_id}/runs.++ Incremental syncs bound each workflow's run list with created_at_start (watermark minus lookback).+ workflow_run_id is globally unique, so it is a sufficient primary key on its own.+ """+ created_at_start = _created_at_start(config, should_use_incremental_field, db_incremental_field_last_value)++ workflow_ids = list(_iter_workflow_ids(session, base_url, headers, logger))+ if not workflow_ids:+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = 0+ start_page = 1+ if resume is not None and resume.workflow_permanent_id in workflow_ids:+ start_index = workflow_ids.index(resume.workflow_permanent_id)+ start_page = resume.page or 1+ logger.debug(f"Skyvern: resuming runs fan-out from workflow={resume.workflow_permanent_id}, page={start_page}")++ for index in range(start_index, len(workflow_ids)):+ workflow_permanent_id = workflow_ids[index]+ page = start_page if index == start_index else 1+ url = f"{base_url}{config.path.format(workflow_permanent_id=workflow_permanent_id)}"++ # A full refresh (no created_at_start window) must page through every run, or a workflow with+ # more than MAX_PAGES_PER_WORKFLOW * PAGE_SIZE runs would be permanently truncated: later+ # incremental syncs only fetch runs newer than the watermark, so the skipped older pages would+ # never be backfilled. The cap only guards runaway on incremental syncs, whose created_at_start+ # window already bounds the volume.+ while created_at_start is None or page <= MAX_PAGES_PER_WORKFLOW:+ params: dict[str, Any] = {"page": page, "page_size": PAGE_SIZE}+ if created_at_start:+ params["created_at_start"] = created_at_start+ data = _fetch_page(session, url, params, headers, logger)+ items = _extract_items(data, config.data_key)+ if not items:+ break++ yield items++ if len(items) < PAGE_SIZE:+ break+ page += 1+ resumable_source_manager.save_state(+ SkyvernResumeConfig(page=page, workflow_permanent_id=workflow_permanent_id)+ )+ else:+ logger.warning(+ "Skyvern: per-workflow incremental run page cap reached; some runs within the "+ "lookback window may be skipped until the next full refresh",+ workflow_permanent_id=workflow_permanent_id,+ max_pages=MAX_PAGES_PER_WORKFLOW,+ )++ # Advance the bookmark to the next workflow so a crash between workflows resumes correctly.+ if index + 1 < len(workflow_ids):+ resumable_source_manager.save_state(+ SkyvernResumeConfig(page=1, workflow_permanent_id=workflow_ids[index + 1])+ )+++def get_rows(+ api_key: str,+ base_url: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SkyvernResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SKYVERN_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ resolved_base_url = _base_url(base_url)+ # base_url is user-supplied — pin redirects off as an SSRF boundary so a hostile host can't+ # redirect the credentialed request to an internal address (see validate_credentials).+ session = make_tracked_session(allow_redirects=False)++ if config.fan_out_over_workflows:+ yield from _get_fan_out_rows(+ session,+ resolved_base_url,+ headers,+ logger,+ resumable_source_manager,+ config,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ return++ yield from _get_simple_rows(session, resolved_base_url, headers, logger, resumable_source_manager, config)+++def skyvern_source(+ api_key: str,+ base_url: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SkyvernResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = SKYVERN_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ base_url=base_url,+ 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=endpoint_config.primary_keys,+ # Skyvern list endpoints return newest-first and expose no sort param, so rows arrive+ # descending by created_at. In desc mode the pipeline persists the incremental watermark only+ # at successful job end, which is what we want for the runs fan-out: a partial run's max+ # created_at says nothing about workflows it never reached.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/source.pyindex 2d04986cd58b..595e0963cbad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/source.py@@ -1,31 +1,168 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SkyvernSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SKYVERN_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.skyvern import (+ SkyvernResumeConfig,+ skyvern_source,+ validate_credentials as validate_skyvern_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SkyvernSource(SimpleSource[SkyvernSourceConfig]):+class SkyvernSource(ResumableSource[SkyvernSourceConfig, SkyvernResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SKYVERN+ @property+ def connection_host_fields(self) -> list[str]:+ # The API key is sent to whatever host `base_url` points at, so retargeting it must re-require+ # the secret — otherwise an editor could change only `base_url` (the masked key is preserved on+ # edit) and exfiltrate the stored key to a host they control.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SKYVERN,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Skyvern",+ releaseStatus=ReleaseStatus.ALPHA,+ unreleasedSource=True,+ caption="""Enter your Skyvern API key to automatically pull your Skyvern browser-automation data into the PostHog Data warehouse.++You can find your API key in your [Skyvern settings](https://app.skyvern.com/settings).++If you self-host Skyvern, set the base URL to your deployment (for example `http://localhost:8000`). Leave it blank to use Skyvern Cloud.""",iconPath="/static/services/skyvern.png",+ docsUrl="https://posthog.com/docs/cdp/sources/skyvern",keywords=["browser automation", "ai agent", "rpa", "workflows"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="Base URL (self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://api.skyvern.com",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing or revoked API key surfaces as a requests HTTPError when a page fetch calls+ # raise_for_status(). Retrying can never satisfy a credential problem, so stop the sync.+ # Matched on the stable status text (host-agnostic since the base URL is configurable).+ "401 Client Error: Unauthorized": "Your Skyvern API key is invalid or has been revoked. Create a new key in your Skyvern settings, then reconnect.",+ "403 Client Error: Forbidden": "Your Skyvern API key does not have permission to access this data. Check the key and reconnect.",+ }++ def get_schemas(+ self,+ config: SkyvernSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "runs":+ return (+ "Task and workflow run history, pulled per workflow. Incremental sync filters on the "+ "immutable created_at with a lookback window; a run whose status changes after it falls "+ "below the watermark is only re-fetched on a full refresh"+ )+ if endpoint == "credentials":+ return "Stored credential metadata only — secret values are never returned by the Skyvern API"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = SKYVERN_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ detected_primary_keys=endpoint_config.primary_keys,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: SkyvernSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_skyvern_credentials(config.api_key, config.base_url)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SkyvernResumeConfig]:+ return ResumableSourceManager[SkyvernResumeConfig](inputs, SkyvernResumeConfig)++ def source_for_pipeline(+ self,+ config: SkyvernSourceConfig,+ resumable_source_manager: ResumableSourceManager[SkyvernResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return skyvern_source(+ api_key=config.api_key,+ base_url=config.base_url,+ 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/skyvern/tests/test_skyvern.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/tests/test_skyvern.pynew file mode 100644index 000000000000..c393f6ed08fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/tests/test_skyvern.py@@ -0,0 +1,220 @@+from datetime import UTC, datetime, timedelta+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern import skyvern+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.settings import SKYVERN_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.skyvern import (+ SkyvernResumeConfig,+ _created_at_start,+ _extract_items,+ get_rows,+ skyvern_source,+ validate_credentials,+)++RUNS_CONFIG = SKYVERN_ENDPOINTS["runs"]+++class FakeResumableManager:+ """In-memory stand-in for ResumableSourceManager that records saved states."""++ def __init__(self, state: Any = None):+ self._state = state+ self.saved: list[Any] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> Any:+ return self._state++ def save_state(self, data: Any) -> None:+ self.saved.append(data)+++class TestCreatedAtStart:+ def test_none_when_not_incremental(self):+ # A full-refresh run (should_use_incremental_field False) must not send a created_at_start,+ # otherwise the first sync would silently window out history.+ assert _created_at_start(RUNS_CONFIG, False, datetime(2026, 1, 10, tzinfo=UTC)) is None++ def test_none_when_no_value(self):+ assert _created_at_start(RUNS_CONFIG, True, None) is None++ def test_applies_lookback(self):+ # The 3-day lookback is what lets a run whose status mutated after creation get re-pulled;+ # dropping it would freeze recently-created runs at their first-seen status.+ result = _created_at_start(RUNS_CONFIG, True, datetime(2026, 1, 10, 12, 0, 0, tzinfo=UTC))+ assert result is not None+ parsed = datetime.fromisoformat(result.replace("Z", "+00:00"))+ assert parsed == datetime(2026, 1, 7, 12, 0, 0, tzinfo=UTC)++ def test_clamps_future_value_to_now(self):+ # A future-dated watermark would filter out every existing run; clamping keeps the sync valid.+ result = _created_at_start(RUNS_CONFIG, True, datetime(2999, 1, 1, tzinfo=UTC))+ assert result is not None+ parsed = datetime.fromisoformat(result.replace("Z", "+00:00"))+ assert parsed <= datetime.now(UTC) + timedelta(seconds=1)+++class TestExtractItems:+ @pytest.mark.parametrize(+ "data,data_key,expected",+ [+ ([{"a": 1}, {"a": 2}], None, [{"a": 1}, {"a": 2}]),+ # /v1/schedules wraps rows under "schedules"; without the unwrap the table syncs zero rows.+ ({"schedules": [{"s": 1}], "total_count": 1}, "schedules", [{"s": 1}]),+ ({"schedules": None}, "schedules", []),+ ({"unexpected": []}, None, []),+ ([], None, []),+ ],+ )+ def test_extract(self, data, data_key, expected):+ assert _extract_items(data, data_key) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code,expected_valid",+ [(200, True), (401, False), (403, False), (500, False)],+ )+ def test_status_mapping(self, status_code, expected_valid):+ response = mock.MagicMock()+ response.status_code = status_code+ session = mock.MagicMock()+ session.get.return_value = response+ with mock.patch.object(skyvern, "make_tracked_session", return_value=session):+ valid, _ = validate_credentials("key", None)+ assert valid is expected_valid++ def test_uses_configured_base_url(self):+ response = mock.MagicMock()+ response.status_code = 200+ session = mock.MagicMock()+ session.get.return_value = response+ with mock.patch.object(skyvern, "make_tracked_session", return_value=session):+ validate_credentials("key", "http://localhost:8000/")+ called_url = session.get.call_args[0][0]+ assert called_url == "http://localhost:8000/v1/agents"+++class TestSimplePagination:+ def test_paginates_until_short_page_and_saves_resume_state(self):+ # Guards the termination condition and resume checkpoint: a full page must continue, a short+ # page must stop, and the next page must be saved after each yield so a crash re-fetches it.+ manager = FakeResumableManager()+ pages = [+ [{"id": "1"}, {"id": "2"}], # full page (PAGE_SIZE patched to 2) -> continue+ [{"id": "3"}], # short page -> stop+ ]+ with (+ mock.patch.object(skyvern, "PAGE_SIZE", 2),+ mock.patch.object(skyvern, "make_tracked_session", return_value=mock.MagicMock()),+ mock.patch.object(skyvern, "_fetch_page", side_effect=pages),+ ):+ batches = list(+ get_rows("key", None, "browser_profiles", mock.MagicMock(), manager) # type: ignore[arg-type]+ )++ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]+ assert manager.saved == [SkyvernResumeConfig(page=2)]++ def test_resumes_from_saved_page(self):+ manager = FakeResumableManager(state=SkyvernResumeConfig(page=5))+ captured: list[dict] = []++ def fetch(session, url, params, headers, logger):+ captured.append(params)+ return [{"id": "x"}]++ with (+ mock.patch.object(skyvern, "PAGE_SIZE", 100),+ mock.patch.object(skyvern, "make_tracked_session", return_value=mock.MagicMock()),+ mock.patch.object(skyvern, "_fetch_page", side_effect=fetch),+ ):+ list(get_rows("key", None, "browser_profiles", mock.MagicMock(), manager)) # type: ignore[arg-type]++ assert captured[0]["page"] == 5+++class TestFanOutRuns:+ def test_fans_out_over_workflows_with_incremental_filter(self):+ # Guards the whole runs strategy: enumerate workflows, then hit each workflow's runs endpoint+ # with created_at_start. A regression that stopped passing created_at_start would turn every+ # incremental sync into a full-history refetch; one that dropped a workflow would lose its runs.+ manager = FakeResumableManager()+ run_params: list[tuple[str, dict]] = []++ def fetch(session, url, params, headers, logger):+ if url.endswith("/v1/agents"):+ return [{"workflow_permanent_id": "wpid_1"}, {"workflow_permanent_id": "wpid_2"}]+ run_params.append((url, dict(params)))+ return [{"workflow_run_id": f"wr_{url.split('/')[-2]}", "created_at": "2026-01-10T00:00:00Z"}]++ with (+ mock.patch.object(skyvern, "make_tracked_session", return_value=mock.MagicMock()),+ mock.patch.object(skyvern, "_fetch_page", side_effect=fetch),+ ):+ batches = list(+ get_rows(+ "key",+ None,+ "runs",+ mock.MagicMock(),+ manager, # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 9, tzinfo=UTC),+ )+ )++ run_ids = {row["workflow_run_id"] for batch in batches for row in batch}+ assert run_ids == {"wr_wpid_1", "wr_wpid_2"}+ assert all("created_at_start" in params for _, params in run_params)++ def test_resumes_from_bookmarked_workflow(self):+ # A saved bookmark must skip already-completed workflows, not restart from the first one.+ manager = FakeResumableManager(state=SkyvernResumeConfig(page=1, workflow_permanent_id="wpid_2"))+ hit_run_urls: list[str] = []++ def fetch(session, url, params, headers, logger):+ if url.endswith("/v1/agents"):+ return [{"workflow_permanent_id": "wpid_1"}, {"workflow_permanent_id": "wpid_2"}]+ hit_run_urls.append(url)+ return [{"workflow_run_id": "wr_1", "created_at": "2026-01-10T00:00:00Z"}]++ with (+ mock.patch.object(skyvern, "make_tracked_session", return_value=mock.MagicMock()),+ mock.patch.object(skyvern, "_fetch_page", side_effect=fetch),+ ):+ list(get_rows("key", None, "runs", mock.MagicMock(), manager)) # type: ignore[arg-type]++ assert all("wpid_2" in url for url in hit_run_urls)+ assert not any("wpid_1" in url for url in hit_run_urls)+++class TestSourceResponse:+ @pytest.mark.parametrize(+ "endpoint,expected_primary_keys,expected_partition",+ [+ ("workflows", ["workflow_permanent_id"], "created_at"),+ ("runs", ["workflow_run_id"], "created_at"),+ ("schedules", ["workflow_schedule_id"], "created_at"),+ ("browser_profiles", ["browser_profile_id"], "created_at"),+ ("credentials", ["credential_id"], None),+ ],+ )+ def test_response_shape(self, endpoint, expected_primary_keys, expected_partition):+ response = skyvern_source("key", None, endpoint, mock.MagicMock(), mock.MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ # Skyvern lists return newest-first, so the pipeline must checkpoint in desc mode.+ assert response.sort_mode == "desc"+ if expected_partition is None:+ assert response.partition_keys is None+ assert response.partition_mode is None+ else:+ assert response.partition_keys == [expected_partition]+ assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/tests/test_skyvern_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/tests/test_skyvern_source.pynew file mode 100644index 000000000000..5fa9ddf14372--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skyvern/tests/test_skyvern_source.py@@ -0,0 +1,117 @@+import pytest+from unittest import mock++import structlog++from posthog.schema import SourceFieldInputConfig++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 SkyvernSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.skyvern import SkyvernResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.skyvern.source import SkyvernSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _inputs() -> SourceInputs:+ return SourceInputs(+ schema_name="runs",+ schema_id="s1",+ source_id="src1",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job1",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestSkyvernSource:+ def setup_method(self):+ self.source = SkyvernSource()+ self.team_id = 1++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.SKYVERN++ @pytest.mark.parametrize(+ "error_message",+ [+ "401 Client Error: Unauthorized for url: https://api.skyvern.com/v1/agents?page=1",+ "403 Client Error: Forbidden for url: http://localhost:8000/v1/runs?page=1",+ ],+ )+ def test_auth_errors_are_non_retryable(self, error_message):+ # The framework substring-matches these keys against the raised error, so a revoked key must+ # fail fast instead of retrying forever. The match must be host-agnostic since the base URL is+ # configurable (self-hosted).+ keys = self.source.get_non_retryable_errors()+ assert any(key in error_message for key in keys)++ @pytest.mark.parametrize(+ "endpoint,expected_incremental,expected_primary_keys",+ [+ # Only runs has a server-side timestamp filter (created_at_start); everything else must be+ # full-refresh so the picker never offers an incremental mode that would sync nothing.+ ("runs", True, ["workflow_run_id"]),+ ("workflows", False, ["workflow_permanent_id"]),+ ("schedules", False, ["workflow_schedule_id"]),+ ("browser_profiles", False, ["browser_profile_id"]),+ ("credentials", False, ["credential_id"]),+ ],+ )+ def test_schema_sync_capabilities(self, endpoint, expected_incremental, expected_primary_keys):+ config = SkyvernSourceConfig(api_key="k")+ schemas = {s.name: s for s in self.source.get_schemas(config, self.team_id)}++ schema = schemas[endpoint]+ assert schema.supports_incremental is expected_incremental+ assert schema.supports_append is False+ assert schema.detected_primary_keys == expected_primary_keys++ def test_get_schemas_can_filter_by_name(self):+ config = SkyvernSourceConfig(api_key="k")+ schemas = self.source.get_schemas(config, self.team_id, names=["runs"])+ assert [s.name for s in schemas] == ["runs"]++ def test_public_docs_table_catalog_renders(self):+ # lists_tables_without_credentials=True means the posthog.com <SourceTables /> section is fed by+ # this catalog built from a credential-free placeholder config. If it broke (bad canonical+ # import, get_schemas needing real creds), the public doc would silently show no tables.+ tables = self.source.get_documented_tables()+ names = {t["name"] for t in tables}+ assert names == {"workflows", "runs", "schedules", "browser_profiles", "credentials"}+ assert all(t["description"] for t in tables)+ runs = next(t for t in tables if t["name"] == "runs")+ assert "Incremental" in runs["sync_methods"]++ def test_validate_credentials_plumbs_key_and_base_url(self):+ config = SkyvernSourceConfig(api_key="secret", base_url="http://localhost:8000")+ with mock.patch.object(+ source_module, "validate_skyvern_credentials", return_value=(True, None)+ ) as mock_validate:+ result = self.source.validate_credentials(config, self.team_id)++ assert result == (True, None)+ mock_validate.assert_called_once_with("secret", "http://localhost:8000")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(_inputs())+ assert manager._data_class is SkyvernResumeConfig++ def test_config_has_required_api_key_and_optional_base_url(self):+ # api_key must stay a required secret and base_url optional, or self-hosted setup breaks and+ # the key stops being masked in the wizard.+ fields = {f.name: f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)}+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True+ assert fields["base_url"].required is False++ def test_base_url_is_a_connection_host_field(self):+ # base_url decides where the API key is sent, so retargeting it must re-require the secret —+ # otherwise the stored key could be exfiltrated to an attacker-controlled host on edit.+ assert self.source.connection_host_fields == ["base_url"]