Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement vellum import source (#70028)

Tom Owersfc4349435867
diff --git a/frontend/public/services/vellum.svg b/frontend/public/services/vellum.svg
new file mode 100644
index 000000000000..09f72a126458
--- /dev/null
+++ b/frontend/public/services/vellum.svg
@@ -0,0 +1,28 @@
+<svg width="177" height="177" viewBox="0 0 177 177" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g filter="url(#filter0_di_85_161)">
+<rect x="2" y="1" width="173" height="173" rx="24" fill="url(#paint0_radial_85_161)"/>
+<path d="M65.2927 45L87.5854 93.3893L109.79 45H132.171L87.4084 137.09L43 45H65.2927Z" fill="white"/>
+</g>
+<defs>
+<filter id="filter0_di_85_161" x="0" y="0" width="177" height="177" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.15 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_85_161"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_85_161" result="shape"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feOffset dy="-1"/>
+<feGaussianBlur stdDeviation="1"/>
+<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1"/>
+<feColorMatrix type="matrix" values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.2 0"/>
+<feBlend mode="normal" in2="shape" result="effect2_innerShadow_85_161"/>
+</filter>
+<radialGradient id="paint0_radial_85_161" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(88.5 -123.344) rotate(90) scale(362.219 174.427)">
+<stop stop-color="#7A8B6F"/>
+<stop offset="1" stop-color="#23793D"/>
+</radialGradient>
+</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.md
index 62333eadd9e8..e31d257f426e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -399,6 +399,7 @@ the row lists both.
| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ubidots | HTTP | requests | ✅ |
| unleash | HTTP | requests | ✅ |
+| vellum | HTTP | requests | ✅ |
| vercel | HTTP | requests | ✅ |
| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
| webflow | HTTP | requests | ✅ |
@@ -838,7 +839,6 @@ doesn't conflict with concurrent PRs.
- vantage
- vapi
- veeqo
-- vellum
- vespa
- visma_economic
- vultr
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 0741ec458919..39b9e2981cb5 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
@@ -3952,7 +3952,7 @@ class VeeqoSourceConfig(config.Config):
@config.config
class VellumSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/canonical_descriptions.py
new file mode 100644
index 000000000000..79618f0d343b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/canonical_descriptions.py
@@ -0,0 +1,83 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from Vellum's public API reference (https://docs.vellum.ai/api-reference).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "workflow_deployments": {
+ "description": "Deployed Vellum workflows, one row per workflow deployment in the environment the API key is scoped to.",
+ "docs_url": "https://docs.vellum.ai/api-reference/api-reference/workflow-deployments/list",
+ "columns": {
+ "id": "Vellum-generated ID that uniquely identifies this workflow deployment.",
+ "name": "A name that uniquely identifies this workflow deployment within its workspace.",
+ "label": "A human-readable label for the workflow deployment.",
+ "status": "The current status of the workflow deployment (ACTIVE, ARCHIVED, or PENDING_DELETION).",
+ "environment": "Deprecated. The value returned will always be 'PRODUCTION'.",
+ "created": "Timestamp representing when this workflow deployment was created.",
+ "last_deployed_on": "Timestamp representing when this workflow deployment was most recently deployed.",
+ "input_variables": "The input variables this workflow deployment expects when executed.",
+ "output_variables": "The output variables this workflow deployment produces when executed.",
+ "description": "A human-readable description of the workflow deployment.",
+ },
+ },
+ "prompt_deployments": {
+ "description": "Deployed Vellum prompts, one row per prompt deployment in the environment the API key is scoped to.",
+ "docs_url": "https://docs.vellum.ai/api-reference/api-reference/deployments/list",
+ "columns": {
+ "id": "Vellum-generated ID that uniquely identifies this prompt deployment.",
+ "name": "A name that uniquely identifies this deployment within its workspace.",
+ "label": "A human-readable label for the deployment.",
+ "status": "The current status of the deployment (ACTIVE, ARCHIVED, or PENDING_DELETION).",
+ "environment": "Deprecated. The value returned will always be 'PRODUCTION'.",
+ "created": "Timestamp representing when this deployment was created.",
+ "last_deployed_on": "Timestamp representing when this deployment was most recently deployed.",
+ "input_variables": "The input variables this deployment expects when executed.",
+ "description": "A human-readable description of the deployment.",
+ },
+ },
+ "document_indexes": {
+ "description": "RAG document indexes used to store and search over uploaded documents.",
+ "docs_url": "https://docs.vellum.ai/api-reference/api-reference/document-indexes/list",
+ "columns": {
+ "id": "Vellum-generated ID that uniquely identifies this document index.",
+ "name": "A name that uniquely identifies this index within its workspace.",
+ "label": "A human-readable label for the document index.",
+ "status": "The current status of the document index (ACTIVE, ARCHIVED, or PENDING_DELETION).",
+ "created": "Timestamp representing when this document index was created.",
+ "indexing_config": "The configuration used to chunk, embed, and index documents in this index.",
+ },
+ },
+ "documents": {
+ "description": "Documents uploaded to Vellum for indexing and retrieval.",
+ "docs_url": "https://docs.vellum.ai/api-reference/api-reference/documents/list",
+ "columns": {
+ "id": "Vellum-generated ID that uniquely identifies this document.",
+ "external_id": "The external ID that was originally provided when uploading the document.",
+ "last_uploaded_at": "Timestamp representing when this document was most recently uploaded.",
+ "label": "Human-friendly name for this document.",
+ "processing_state": "The current processing state of the document.",
+ "processing_failure_reason": "Why the document could not be processed. Null unless processing_state is FAILED.",
+ "status": "The document's current status.",
+ "keywords": "A list of keywords associated with this document, provided at upload time.",
+ "metadata": "A JSON object of metadata that can be filtered on when searching.",
+ "document_to_document_indexes": "The indexes this document has been added to, with per-index processing state.",
+ },
+ },
+ "workflow_execution_events": {
+ "description": "Per-execution history for each workflow deployment: inputs, outputs, timing, and errors for every run. One row per execution span, keyed by the parent workflow deployment and the span id.",
+ "docs_url": "https://docs.vellum.ai/api-reference/api-reference/workflow-deployments/list-workflow-deployment-event-executions",
+ "columns": {
+ "workflow_deployment_id": "ID of the workflow deployment this execution belongs to (injected by PostHog during the fan-out).",
+ "span_id": "Vellum-generated ID that uniquely identifies this execution span.",
+ "start": "Timestamp representing when this execution started.",
+ "end": "Timestamp representing when this execution finished. Null while still running.",
+ "inputs": "The input values this execution was invoked with.",
+ "outputs": "The output values this execution produced.",
+ "error": "Error details if the execution failed.",
+ "usage_results": "Token usage and cost information for the execution.",
+ "parent_context": "Context about the parent that triggered this execution, if any.",
+ "latest_actual": "The most recent actual/feedback value recorded against this execution.",
+ "metric_results": "Metric evaluation results recorded for this execution.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/settings.py
new file mode 100644
index 000000000000..645e552dea12
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/settings.py
@@ -0,0 +1,72 @@
+from dataclasses import dataclass, field
+
+# Environment-scoped API keys mean one key syncs one Vellum environment (Development/Staging/Production).
+# Self-hosted/VPC customers have account-specific base URLs, but the managed cloud API lives here.
+VELLUM_BASE_URL = "https://api.vellum.ai/v1"
+
+
+@dataclass
+class VellumEndpointConfig:
+ name: str
+ # Path relative to VELLUM_BASE_URL. Fan-out endpoints carry a `{deployment_id}` placeholder.
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable created-style field used to partition the Delta table. Never a mutable field like
+ # `last_deployed_on` / `last_uploaded_at`, which would rewrite partitions on every sync.
+ partition_key: str | None = None
+ # Value passed as `?ordering=` for a deterministic page order across the offset walk. Left None
+ # when the resource exposes no stable orderable timestamp (Vellum silently accepts unknown
+ # ordering values, so we only send one we can reason about).
+ ordering: str | None = None
+ should_sync_default: bool = True
+ # Fan out over every workflow deployment, hitting `path` (with `{deployment_id}`) per parent to
+ # pull its execution history. The parent id is injected into each child row under
+ # `parent_id_field` so the composite primary key stays unique table-wide.
+ fan_out_over_workflow_deployments: bool = False
+ parent_id_field: str | None = None
+
+
+VELLUM_ENDPOINTS: dict[str, VellumEndpointConfig] = {
+ # Deployed workflows. `created` is immutable; `last_deployed_on` is not, so it is never the partition key.
+ "workflow_deployments": VellumEndpointConfig(
+ name="workflow_deployments",
+ path="/workflow-deployments",
+ partition_key="created",
+ ordering="created",
+ ),
+ # Deployed prompts (Vellum calls these simply "deployments").
+ "prompt_deployments": VellumEndpointConfig(
+ name="prompt_deployments",
+ path="/deployments",
+ partition_key="created",
+ ordering="created",
+ ),
+ # RAG document indexes.
+ "document_indexes": VellumEndpointConfig(
+ name="document_indexes",
+ path="/document-indexes",
+ partition_key="created",
+ ordering="created",
+ ),
+ # Documents uploaded for indexing. Exposes only `last_uploaded_at` (mutable on re-upload), so no
+ # partition key and no ordering — full refresh with merge dedup on `id`.
+ "documents": VellumEndpointConfig(
+ name="documents",
+ path="/documents",
+ ),
+ # Per-workflow-deployment execution history — the richest historical stream (per-execution inputs,
+ # outputs, timing). Fans out one paginated request per workflow deployment. `span_id` is unique per
+ # execution but the key is composite with the parent id so rows aggregated across deployments stay
+ # unique table-wide. Opt-in (off by default) because it multiplies API calls by the deployment count.
+ "workflow_execution_events": VellumEndpointConfig(
+ name="workflow_execution_events",
+ path="/workflow-deployments/{deployment_id}/execution-events",
+ primary_keys=["workflow_deployment_id", "span_id"],
+ partition_key="start",
+ should_sync_default=False,
+ fan_out_over_workflow_deployments=True,
+ parent_id_field="workflow_deployment_id",
+ ),
+}
+
+ENDPOINTS = tuple(VELLUM_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/source.py
index 5cc04cb90653..b3426e5af893 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/source.py
@@ -1,19 +1,39 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import VellumSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.vellum.settings import ENDPOINTS, VELLUM_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.vellum.vellum import (
+ VellumResumeConfig,
+ check_credentials,
+ vellum_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class VellumSource(SimpleSource[VellumSourceConfig]):
+class VellumSource(ResumableSource[VellumSourceConfig, VellumResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.VELLUM
@@ -24,8 +44,93 @@ class VellumSource(SimpleSource[VellumSourceConfig]):
name=SchemaExternalDataSourceType.VELLUM,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Vellum",
- iconPath="/static/services/vellum.png",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Vellum API key to sync your Vellum deployments, documents, and execution history into the PostHog Data warehouse.
+
+You can create an API key in your Vellum [workspace settings](https://app.vellum.ai/api-keys). Vellum API keys are environment-scoped (Development / Staging / Production), so one key syncs one environment.""",
+ iconPath="/static/services/vellum.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/vellum",
keywords=["llm", "observability", "prompts", "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,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.vellum.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked Vellum API key surfaces as a 403 when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.
+ # Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.vellum.ai": "Your Vellum API key is invalid or has been revoked. Create a new key in your Vellum workspace settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.vellum.ai": "Your Vellum API key is invalid or missing the permissions needed to sync this data. Check the key in your Vellum workspace settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: VellumSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = VELLUM_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ # Vellum's list endpoints expose no server-side timestamp filter (a `created__gte`
+ # cutoff is silently ignored), so every sync is a full refresh.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ 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: VellumSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ ok, status = check_credentials(config.api_key)
+ if ok:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Vellum API key"
+ return False, "Could not connect to Vellum. Please try again later."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[VellumResumeConfig]:
+ return ResumableSourceManager[VellumResumeConfig](inputs, VellumResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: VellumSourceConfig,
+ resumable_source_manager: ResumableSourceManager[VellumResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return vellum_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/tests/test_vellum.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/tests/test_vellum.py
new file mode 100644
index 000000000000..65952bc65a55
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/tests/test_vellum.py
@@ -0,0 +1,261 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.vellum import vellum
+from products.warehouse_sources.backend.temporal.data_imports.sources.vellum.settings import VELLUM_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.vellum.vellum import (
+ VellumResumeConfig,
+ get_rows,
+ vellum_source,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: VellumResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[VellumResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> VellumResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: VellumResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _response_with_status(status_code: int) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ return response
+
+
+def _collect(manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: dict) -> list[dict]:
+ """Drive get_rows with a fake `_fetch_page` keyed by request URL + offset."""
+
+ def fake_fetch(session: Any, url: str, headers: dict, params: dict, logger: Any) -> dict:
+ result = pages[(url, params["offset"])]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(vellum, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(
+ api_key="test-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+DOCUMENTS_URL = "https://api.vellum.ai/v1/documents"
+WFD_URL = "https://api.vellum.ai/v1/workflow-deployments"
+
+
+class TestOffsetPagination:
+ def test_walks_offsets_and_stops_at_count(self, monkeypatch: Any) -> None:
+ # offset must advance by the number of rows actually returned, and pagination must stop once
+ # the accumulated offset reaches `count` — a wrong terminator either loops forever or truncates.
+ pages = {
+ (DOCUMENTS_URL, 0): {"count": 3, "results": [{"id": "d1"}, {"id": "d2"}]},
+ (DOCUMENTS_URL, 2): {"count": 3, "results": [{"id": "d3"}]},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "documents", pages)
+ assert rows == [{"id": "d1"}, {"id": "d2"}, {"id": "d3"}]
+
+ def test_stops_on_short_page_without_count(self, monkeypatch: Any) -> None:
+ # The execution-events response carries no `next`; an empty page is the only stop signal.
+ pages = {
+ (DOCUMENTS_URL, 0): {"results": [{"id": "d1"}]},
+ (DOCUMENTS_URL, 1): {"results": []},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "documents", pages)
+ assert rows == [{"id": "d1"}]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ # A resumed run must skip pages already synced; starting from offset 0 would redo work.
+ pages = {(DOCUMENTS_URL, 2): {"count": 3, "results": [{"id": "d3"}]}}
+ manager = _FakeResumableManager(VellumResumeConfig(offset=2))
+ rows = _collect(manager, monkeypatch, "documents", pages)
+ assert rows == [{"id": "d3"}]
+
+ def test_saved_offset_is_current_page_not_next(self, monkeypatch: Any) -> None:
+ # Saving the *current* page offset means a crash re-fetches this page and merge dedupes;
+ # saving the next page's offset would skip the page's unyielded tail on resume.
+ pages = {
+ (DOCUMENTS_URL, 0): {"count": 4, "results": [{"id": "d1"}, {"id": "d2"}]},
+ (DOCUMENTS_URL, 2): {"count": 4, "results": [{"id": "d3"}, {"id": "d4"}]},
+ }
+ manager = _FakeResumableManager()
+
+ def fake_fetch(session: Any, url: str, headers: dict, params: dict, logger: Any) -> dict:
+ return pages[(url, params["offset"])]
+
+ monkeypatch.setattr(vellum, "_fetch_page", fake_fetch)
+ # chunk_size=1 forces a yield (and a save) after every row.
+ batcher = Batcher(logger=MagicMock(), chunk_size=1, chunk_size_bytes=100 * 1024 * 1024)
+ list(
+ vellum._paginate(
+ MagicMock(),
+ DOCUMENTS_URL,
+ {},
+ MagicMock(),
+ batcher,
+ manager, # type: ignore[arg-type]
+ ordering=None,
+ start_offset=0,
+ deployment_id=None,
+ )
+ )
+ # Rows from page-1 save offset 0, rows from page-2 save offset 2 — never 2 while still on page 1.
+ assert [s.offset for s in manager.saved] == [0, 0, 2, 2]
+
+ def test_ordering_param_sent_when_configured(self, monkeypatch: Any) -> None:
+ # workflow_deployments paginates oldest-first via ?ordering=created for a stable page order;
+ # dropping it risks page-boundary skips/dupes as rows are inserted mid-sync.
+ seen: list[dict] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, params: dict, logger: Any) -> dict:
+ seen.append(params)
+ return {"count": 0, "results": []}
+
+ monkeypatch.setattr(vellum, "_fetch_page", fake_fetch)
+ list(get_rows("k", "workflow_deployments", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]
+ assert seen[0]["ordering"] == "created"
+ # documents has no stable created field, so no ordering is forced.
+ seen.clear()
+ list(get_rows("k", "documents", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]
+ assert "ordering" not in seen[0]
+
+
+EVENTS_A = "https://api.vellum.ai/v1/workflow-deployments/A/execution-events"
+EVENTS_B = "https://api.vellum.ai/v1/workflow-deployments/B/execution-events"
+
+
+class TestExecutionEventsFanOut:
+ def test_config_is_opt_in_fan_out_with_composite_pk(self) -> None:
+ config = VELLUM_ENDPOINTS["workflow_execution_events"]
+ assert config.fan_out_over_workflow_deployments is True
+ assert config.should_sync_default is False
+ assert config.primary_keys == ["workflow_deployment_id", "span_id"]
+
+ def test_injects_parent_id_into_every_row(self, monkeypatch: Any) -> None:
+ # The parent id completes the composite key; without it rows from different deployments that
+ # share a span id would collide and every merge would multi-match (the OOM failure mode).
+ pages = {
+ (WFD_URL, 0): {"count": 2, "results": [{"id": "A"}, {"id": "B"}]},
+ (EVENTS_A, 0): {"count": 1, "results": [{"span_id": "s1", "start": "2026-01-01T00:00:00Z"}]},
+ (EVENTS_B, 0): {"count": 1, "results": [{"span_id": "s2", "start": "2026-01-02T00:00:00Z"}]},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "workflow_execution_events", pages)
+ assert rows == [
+ {"workflow_deployment_id": "A", "span_id": "s1", "start": "2026-01-01T00:00:00Z"},
+ {"workflow_deployment_id": "B", "span_id": "s2", "start": "2026-01-02T00:00:00Z"},
+ ]
+
+ def test_deployment_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:
+ not_found = requests.HTTPError(response=_response_with_status(404))
+ pages = {
+ (WFD_URL, 0): {"count": 2, "results": [{"id": "A"}, {"id": "B"}]},
+ (EVENTS_A, 0): not_found,
+ (EVENTS_B, 0): {"count": 1, "results": [{"span_id": "s2", "start": "2026-01-02T00:00:00Z"}]},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "workflow_execution_events", pages)
+ assert rows == [{"workflow_deployment_id": "B", "span_id": "s2", "start": "2026-01-02T00:00:00Z"}]
+
+ def test_non_404_error_propagates(self, monkeypatch: Any) -> None:
+ server_error = requests.HTTPError(response=_response_with_status(500))
+ pages = {
+ (WFD_URL, 0): {"count": 1, "results": [{"id": "A"}]},
+ (EVENTS_A, 0): server_error,
+ }
+ with pytest.raises(requests.HTTPError):
+ _collect(_FakeResumableManager(), monkeypatch, "workflow_execution_events", pages)
+
+ def test_resume_from_bookmarked_deployment(self, monkeypatch: Any) -> None:
+ # Resuming must restart at the bookmarked deployment (B), not re-walk A from the top.
+ pages = {
+ (WFD_URL, 0): {"count": 2, "results": [{"id": "A"}, {"id": "B"}]},
+ (EVENTS_B, 0): {"count": 1, "results": [{"span_id": "s2", "start": "2026-01-02T00:00:00Z"}]},
+ }
+ manager = _FakeResumableManager(VellumResumeConfig(offset=0, deployment_id="B"))
+ rows = _collect(manager, monkeypatch, "workflow_execution_events", pages)
+ assert rows == [{"workflow_deployment_id": "B", "span_id": "s2", "start": "2026-01-02T00:00:00Z"}]
+
+
+class TestFetchPageRetries:
+ @parameterized.expand(
+ [
+ ("chunked_encoding", requests.exceptions.ChunkedEncodingError("Connection broken")),
+ ("read_timeout", requests.ReadTimeout("Read timed out.")),
+ ("connection_error", requests.ConnectionError("Connection reset by peer")),
+ ]
+ )
+ def test_transient_errors_are_retried(self, _name: str, transient_error: Exception) -> None:
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"count": 0, "results": []}
+ session = MagicMock()
+ session.get.side_effect = [transient_error, good]
+
+ with patch.object(vellum._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = vellum._fetch_page(session, WFD_URL, {}, {"offset": 0}, MagicMock())
+
+ assert result == {"count": 0, "results": []}
+ assert session.get.call_count == 2
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_status_codes_retry(self, _name: str, status_code: int) -> None:
+ bad = MagicMock(status_code=status_code)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"count": 0, "results": []}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(vellum._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = vellum._fetch_page(session, WFD_URL, {}, {"offset": 0}, MagicMock())
+
+ assert result == {"count": 0, "results": []}
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_immediately(self) -> None:
+ # A 403 (bad/insufficient key) must surface at once so get_non_retryable_errors can stop the sync.
+ bad = MagicMock(status_code=403, ok=False, text="Invalid API key")
+ bad.raise_for_status.side_effect = requests.HTTPError("403 Client Error: Forbidden", response=bad)
+ session = MagicMock()
+ session.get.return_value = bad
+
+ with pytest.raises(requests.HTTPError):
+ vellum._fetch_page(session, WFD_URL, {}, {"offset": 0}, MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("workflow_deployments", ["id"], "created"),
+ ("prompt_deployments", ["id"], "created"),
+ ("document_indexes", ["id"], "created"),
+ # documents exposes only the mutable last_uploaded_at, so it must not be partitioned.
+ ("documents", ["id"], None),
+ ("workflow_execution_events", ["workflow_deployment_id", "span_id"], "start"),
+ ]
+ )
+ def test_primary_keys_and_partitioning(
+ self, endpoint: str, expected_pks: list[str], expected_partition: str | None
+ ) -> None:
+ response = vellum_source("k", endpoint, MagicMock(), MagicMock())
+ assert response.primary_keys == expected_pks
+ assert response.partition_keys == ([expected_partition] if expected_partition else None)
+ assert response.partition_mode == ("datetime" if expected_partition else None)
+ assert response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/tests/test_vellum_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/tests/test_vellum_source.py
new file mode 100644
index 000000000000..cd6a98da4d29
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/tests/test_vellum_source.py
@@ -0,0 +1,153 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.vellum.source import VellumSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.vellum.vellum import VellumResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestVellumSourceConfig:
+ def test_source_type(self) -> None:
+ assert VellumSource().source_type == ExternalDataSourceType.VELLUM
+
+ def test_source_config_shape(self) -> None:
+ config = VellumSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/vellum"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_single_password_api_key_field(self) -> None:
+ # The only credential is an environment-scoped API key; it must be a masked secret so the
+ # serializer classifies it as sensitive and never echoes it back.
+ fields = VellumSource().get_source_config.fields
+ assert len(fields) == 1
+ api_key = fields[0]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.name == "api_key"
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+ assert api_key.secret is True
+
+
+class TestVellumSchemas:
+ def test_returns_all_endpoints_full_refresh(self) -> None:
+ # Vellum exposes no server-side timestamp filter, so every table is full-refresh only.
+ # supports_incremental leaking to True would let a sync silently drop rows.
+ schemas = {s.name: s for s in VellumSource().get_schemas(MagicMock(), team_id=1)}
+ assert set(schemas) == {
+ "workflow_deployments",
+ "prompt_deployments",
+ "document_indexes",
+ "documents",
+ "workflow_execution_events",
+ }
+ for schema in schemas.values():
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_execution_events_is_opt_in(self) -> None:
+ # The fan-out multiplies API calls by the deployment count, so it must be off by default.
+ schemas = {s.name: s for s in VellumSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas["workflow_execution_events"].should_sync_default is False
+ assert schemas["workflow_deployments"].should_sync_default is True
+
+ def test_names_filter(self) -> None:
+ schemas = VellumSource().get_schemas(MagicMock(), team_id=1, names=["documents"])
+ assert [s.name for s in schemas] == ["documents"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # The catalog is static (no I/O), so public docs can render the table list. If get_schemas ever
+ # starts hitting the network this flag must flip off or the docs endpoint would hang.
+ assert VellumSource().lists_tables_without_credentials is True
+ tables = {t["name"] for t in VellumSource().get_documented_tables()}
+ assert "workflow_deployments" in tables
+
+
+class TestVellumValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid", (True, 200), True, None),
+ ("bad_key_403", (False, 403), False, "Invalid Vellum API key"),
+ ("unauthorized_401", (False, 401), False, "Invalid Vellum API key"),
+ ("network_error", (False, None), False, "Could not connect to Vellum. Please try again later."),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, probe_result: tuple[bool, int | None], expected_ok: bool, expected_msg: str | None
+ ) -> None:
+ source = VellumSource()
+ config = MagicMock(api_key="test-key")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.vellum.source.check_credentials",
+ return_value=probe_result,
+ ):
+ ok, msg = source.validate_credentials(config, team_id=1)
+ assert ok is expected_ok
+ assert msg == expected_msg
+
+
+class TestVellumNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.vellum.ai/v1/documents?limit=100"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.vellum.ai/v1/document-indexes"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ assert any(key in observed_error for key in VellumSource().get_non_retryable_errors())
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.vellum.ai', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.vellum.ai/v1/documents"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.vellum.ai/v1/documents"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ assert not any(key in other_error for key in VellumSource().get_non_retryable_errors())
+
+
+class TestVellumResumableManager:
+ def test_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = VellumSource().get_resumable_source_manager(inputs)
+ assert manager._data_class is VellumResumeConfig
+
+ def test_source_for_pipeline_plumbs_endpoint_and_key(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "documents"
+ inputs.logger = MagicMock()
+ manager = MagicMock()
+ config = MagicMock(api_key="test-key")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.vellum.source.vellum_source"
+ ) as mock_source:
+ VellumSource().source_for_pipeline(config, manager, inputs)
+ _, kwargs = mock_source.call_args
+ assert kwargs["endpoint"] == "documents"
+ assert kwargs["api_key"] == "test-key"
+ assert kwargs["resumable_source_manager"] is manager
+
+
+def _canonical_descriptions() -> dict[str, Any]:
+ return VellumSource().get_canonical_descriptions()
+
+
+class TestVellumCanonicalDescriptions:
+ def test_execution_events_parent_id_documented(self) -> None:
+ # The injected parent id is part of the composite primary key; documenting it keeps the
+ # AI-facing schema honest about a column the API itself never returns.
+ columns = _canonical_descriptions()["workflow_execution_events"]["columns"]
+ assert "workflow_deployment_id" in columns
+ assert "span_id" in columns
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/vellum.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/vellum.py
new file mode 100644
index 000000000000..729d30e3d428
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vellum/vellum.py
@@ -0,0 +1,281 @@
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any
+
+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.batcher import Batcher
+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.vellum.settings import (
+ VELLUM_BASE_URL,
+ VELLUM_ENDPOINTS,
+ VellumEndpointConfig,
+)
+
+PAGE_SIZE = 100
+
+
+class VellumRetryableError(Exception):
+ pass
+
+
+class VellumResumeConfig:
+ # Next `offset` to request for the resource currently being paginated.
+ offset: int = 0
+ # Fan-out only: the workflow deployment whose execution events we're partway through. A stable id
+ # bookmark (not a positional index) so deployments added/removed between a crash and the retry can't
+ # resume us into the wrong parent. None for the standard top-level endpoints.
+ deployment_id: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {"X-API-KEY": api_key, "Accept": "application/json"}
+
+
+def check_credentials(api_key: str) -> tuple[bool, int | None]:
+ """Probe an auth-gated list endpoint. Returns ``(reachable, status_code)``.
+
+ ``/document-indexes`` strictly requires a key (unlike ``/workflow-deployments``, which serves
+ public demo data without one), so a 200 confirms the key is genuinely valid.
+ """
+ url = f"{VELLUM_BASE_URL}/document-indexes"
+ try:
+ # capture=False: Vellum bodies can echo user-authored content (workflow inputs/outputs,
+ # document metadata, descriptions) the name-based scrubbers can't recognise.
+ session = make_tracked_session(redact_values=(api_key,), capture=False)
+ response = session.get(url, headers=_get_headers(api_key), params={"limit": 1}, timeout=10)
+ return response.status_code == 200, response.status_code
+ except Exception:
+ return False, None
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ VellumRetryableError,
+ 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,
+ headers: dict[str, str],
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict:
+ response = session.get(url, headers=headers, params=params, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise VellumRetryableError(f"Vellum API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 is expected during the execution-events fan-out (a deployment deleted mid-sync).
+ # Never log the response body: Vellum error payloads can echo synced execution data
+ # (workflow inputs/outputs), which must not leak into operational logs.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Vellum API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _paginate(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[VellumResumeConfig],
+ ordering: str | None,
+ start_offset: int,
+ deployment_id: str | None,
+ transform: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
+) -> Iterator[Any]:
+ """Walk a Vellum list endpoint via `limit`/`offset` and yield batches.
+
+ Vellum's list responses carry `count`/`results` (top-level endpoints also carry `next`/`previous`,
+ but the execution-events response does not), so we page purely on offset and stop when a page comes
+ back short or the accumulated offset reaches `count`. When a batch is yielded we save the *current*
+ page's offset (not the next page's): a crash then resumes by re-fetching this page and merge dedupes
+ the rows already yielded on the primary key. Advancing the saved offset past the current page could
+ skip its unyielded tail.
+ """
+ offset = start_offset
+ while True:
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset}
+ if ordering:
+ params["ordering"] = ordering
+
+ data = _fetch_page(session, url, headers, params, logger)
+ results = data.get("results", [])
+ count = data.get("count")
+
+ for item in results:
+ batcher.batch(transform(item) if transform else item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ manager.save_state(VellumResumeConfig(offset=offset, deployment_id=deployment_id))
+
+ offset += len(results)
+ if not results or (count is not None and offset >= count):
+ break
+
+
+def _iter_workflow_deployment_ids(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[str]:
+ """Page through /workflow-deployments (oldest-first) yielding each deployment id for the fan-out."""
+ offset = 0
+ while True:
+ params = {"limit": PAGE_SIZE, "offset": offset, "ordering": "created"}
+ data = _fetch_page(session, f"{VELLUM_BASE_URL}/workflow-deployments", headers, params, logger)
+ results = data.get("results", [])
+ if not results:
+ break
+ for item in results:
+ yield item["id"]
+ offset += len(results)
+ count = data.get("count")
+ if count is not None and offset >= count:
+ break
+
+
+def _get_execution_event_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[VellumResumeConfig],
+ config: VellumEndpointConfig,
+) -> Iterator[Any]:
+ """Fan out over every workflow deployment, pulling its execution events and stamping the parent id.
+
+ The parent id is injected under `config.parent_id_field` so the composite primary key
+ (`[workflow_deployment_id, span_id]`) is unique across the whole table. Full refresh: we can't
+ verify Vellum's `filters`/`ordering` params for this endpoint without a live key, so we don't rely
+ on them and merge dedupes across syncs.
+ """
+ # Fan-out configs always set `parent_id_field`; assert it so the child-row injection is well-typed.
+ parent_id_field = config.parent_id_field
+ assert parent_id_field is not None, "fan-out endpoints must define parent_id_field"
+
+ deployment_ids = list(_iter_workflow_deployment_ids(session, headers, logger))
+
+ resume = manager.load_state() if manager.can_resume() else None
+ remaining = deployment_ids
+ resume_offset = 0
+ if resume is not None and resume.deployment_id is not None and resume.deployment_id in deployment_ids:
+ remaining = deployment_ids[deployment_ids.index(resume.deployment_id) :]
+ resume_offset = resume.offset
+ logger.debug(
+ f"Vellum: resuming execution events from deployment_id={resume.deployment_id}, offset={resume_offset}"
+ )
+
+ for index, deployment_id in enumerate(remaining):
+ start_offset = resume_offset
+ resume_offset = 0 # only the resumed-into deployment uses the saved offset
+ url = f"{VELLUM_BASE_URL}{config.path.replace('{deployment_id}', deployment_id)}"
+
+ def _inject_parent_id(
+ item: dict[str, Any], _dep_id: str = deployment_id, _field: str = parent_id_field
+ ) -> dict[str, Any]:
+ item[_field] = _dep_id
+ return item
+
+ try:
+ yield from _paginate(
+ session,
+ url,
+ headers,
+ logger,
+ batcher,
+ manager,
+ ordering=None,
+ start_offset=start_offset,
+ deployment_id=deployment_id,
+ transform=_inject_parent_id,
+ )
+ except requests.HTTPError as exc:
+ # A deployment deleted between enumeration and this fetch 404s. Skip it rather than failing
+ # the whole sync; any other HTTP error is re-raised.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Vellum: workflow deployment {deployment_id} not found while fetching events, skipping")
+ else:
+ raise
+
+ # Advance the bookmark to the next deployment so a crash between deployments resumes correctly.
+ if index + 1 < len(remaining):
+ manager.save_state(VellumResumeConfig(offset=0, deployment_id=remaining[index + 1]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[VellumResumeConfig],
+) -> Iterator[Any]:
+ config = VELLUM_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # capture=False: Vellum bodies can echo user-authored content (workflow inputs/outputs,
+ # document metadata, descriptions) the name-based scrubbers can't recognise.
+ session = make_tracked_session(redact_values=(api_key,), capture=False)
+
+ if config.fan_out_over_workflow_deployments:
+ yield from _get_execution_event_rows(session, headers, logger, batcher, resumable_source_manager, config)
+ else:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_offset = resume.offset if resume is not None else 0
+ if start_offset:
+ logger.debug(f"Vellum: resuming {endpoint} from offset={start_offset}")
+ yield from _paginate(
+ session,
+ f"{VELLUM_BASE_URL}{config.path}",
+ headers,
+ logger,
+ batcher,
+ resumable_source_manager,
+ ordering=config.ordering,
+ start_offset=start_offset,
+ deployment_id=None,
+ )
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def vellum_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[VellumResumeConfig],
+) -> SourceResponse:
+ config = VELLUM_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )