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 trigger_dev import source (#70035)

Tom Owers09600af9d62f
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 d0a2db4d492f..8b74ebf76f76 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -390,6 +390,7 @@ the row lists both.
| together_ai | HTTP | requests | ✅ |
| trello | HTTP | requests | ✅ |
| tremendous | HTTP | requests | ✅ |
+| trigger_dev | HTTP | requests | ✅ |
| twilio | HTTP | requests | ✅ |
| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ubidots | HTTP | requests | ✅ |
@@ -816,7 +817,6 @@ doesn't conflict with concurrent PRs.
- toggl
- track_pms
- tremendous
-- trigger_dev
- trustpilot
- turso
- tvmaze
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
index ea506406ed34..e8a477865222 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
@@ -84,6 +84,16 @@ class ResumableSourceManager(Generic[ResumableData]):
redis.set(self._key, json_data, ex=60 * 60 * 24) # 24 hours expiration
+ def clear_state(self) -> None:
+ """Drop any saved resume state so a subsequent attempt starts from scratch.
+
+ Called once a source has walked its data to completion: leaving the final checkpoint in
+ place would let a later attempt resume mid-stream instead of restarting cleanly.
+ """
+ with self._get_redis() as redis:
+ self._logger.debug(f"Clearing resumable source state. key={self._key}")
+ redis.delete(self._key)
+
def can_resume(self) -> bool:
with self._get_redis() as redis:
exists = redis.exists(self._key) == 1
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 bd3137fb3217..76778db75b67 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
@@ -3827,7 +3827,8 @@ class TremendousSourceConfig(config.Config):
@config.config
class TriggerDevSourceConfig(config.Config):
- pass
+ api_key: str
+ base_url: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/canonical_descriptions.py
new file mode 100644
index 000000000000..102c3b3cee79
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/canonical_descriptions.py
@@ -0,0 +1,60 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "runs": {
+ "description": "A single execution of a Trigger.dev task, with its lifecycle status, timings, and cost.",
+ "docs_url": "https://trigger.dev/docs/management/runs/list",
+ "columns": {
+ "id": "Unique identifier for the run, prefixed with `run_`.",
+ "status": "Current lifecycle status (e.g. QUEUED, EXECUTING, COMPLETED, FAILED, CANCELED, CRASHED).",
+ "taskIdentifier": "Identifier of the task that this run executes.",
+ "version": "Worker version that executed the run (e.g. 20240523.1).",
+ "env": "The environment the run belongs to (id, name, and optional dev username).",
+ "idempotencyKey": "Key used to prevent duplicate runs.",
+ "isTest": "Whether the run was triggered as a test run.",
+ "createdAt": "When the run was created.",
+ "updatedAt": "When the run was last updated.",
+ "startedAt": "When the run started executing.",
+ "finishedAt": "When the run finished.",
+ "delayedUntil": "When a delayed run is scheduled to be enqueued.",
+ "ttl": "Time-to-live before an unstarted run expires (e.g. 1h42m).",
+ "expiredAt": "When the run's TTL passed and it expired.",
+ "tags": "User-defined tags attached to the run (up to 10).",
+ "costInCents": "Compute cost accrued so far, in cents (not set for DEV runs).",
+ "baseCostInCents": "Fixed invocation cost, in cents (not set for DEV runs).",
+ "durationMs": "Compute duration in milliseconds, excluding waits.",
+ },
+ },
+ "schedules": {
+ "description": "A schedule that triggers a task on a recurring cron expression.",
+ "docs_url": "https://trigger.dev/docs/management/schedules/list",
+ "columns": {
+ "id": "Unique identifier for the schedule, prefixed with `sched_`.",
+ "task": "Identifier of the scheduled task this schedule triggers.",
+ "type": "Whether the schedule is DECLARATIVE (defined in code) or IMPERATIVE (created via the API/dashboard).",
+ "active": "Whether the schedule is currently enabled.",
+ "deduplicationKey": "Key used to prevent creating duplicate schedules.",
+ "externalId": "Your own identifier associated with the schedule (e.g. a user or org id).",
+ "generator": "The cron generator: type, cron expression, and a plain-English description.",
+ "timezone": "IANA timezone the cron expression is evaluated in.",
+ "nextRun": "Next scheduled run time.",
+ "environments": "Environments the schedule is attached to.",
+ },
+ },
+ "queues": {
+ "description": "A task queue and its live concurrency and depth counters.",
+ "docs_url": "https://trigger.dev/docs/management/queues/list",
+ "columns": {
+ "id": "Unique identifier for the queue, prefixed with `queue_`.",
+ "name": "Queue name. For task queues this is the task id; for custom queues it is the name you specified.",
+ "type": "Whether the queue is a `task` queue (auto-created) or a `custom` queue (defined in code).",
+ "running": "Number of runs currently executing on the queue.",
+ "queued": "Number of runs currently waiting on the queue.",
+ "paused": "Whether the queue is paused (no new runs will start).",
+ "concurrencyLimit": "The current concurrency limit for the queue, if set.",
+ "concurrency": "Detailed concurrency info (current effective limit, base limit, and any override).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/settings.py
new file mode 100644
index 000000000000..161ccaa69720
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/settings.py
@@ -0,0 +1,76 @@
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class TriggerDevEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField]
+ # "cursor" -> the runs endpoint's page[after]/pagination.next cursor pagination.
+ # "page" -> classic page/perPage pagination (schedules, queues).
+ pagination: Literal["cursor", "page"] = "page"
+ default_incremental_field: Optional[str] = None
+ # Field to partition by. Must be a STABLE creation timestamp (never updatedAt) so partitions
+ # aren't rewritten every sync.
+ partition_key: Optional[str] = None
+ page_size: int = 100 # runs cap at 100; classic endpoints accept the same size comfortably
+ sort_mode: Literal["asc", "desc"] = "asc"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+ # Safety overlap subtracted from the incremental watermark each run. Runs are created immutable,
+ # but their status / updatedAt / cost fields keep mutating after creation, and there is no
+ # updated-since filter — so we re-pull a trailing window of recently created runs to pick up those
+ # late transitions. Merge dedupes the re-pulled rows on the primary key.
+ incremental_lookback: Optional[timedelta] = None
+
+
+TRIGGER_DEV_ENDPOINTS: dict[str, TriggerDevEndpointConfig] = {
+ # Task runs: the execution history. Cursor pagination (page[after] = pagination.next), returned
+ # newest-first by createdAt with no sort param, so we sync incrementally by walking newest-first
+ # and stopping once we cross below the watermark (see trigger_dev.py). createdAt is immutable, so
+ # it is the stable partition/cursor key; the 3-day lookback re-reads recent runs to catch status
+ # changes that land after the run was first synced.
+ "runs": TriggerDevEndpointConfig(
+ name="runs",
+ path="/api/v1/runs",
+ pagination="cursor",
+ default_incremental_field="createdAt",
+ partition_key="createdAt",
+ sort_mode="desc",
+ incremental_lookback=timedelta(days=3),
+ incremental_fields=[
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Schedules are a small, mutable config set (active flag, cron expression, nextRun) with no
+ # creation timestamp or server-side time filter, so full refresh each sync.
+ "schedules": TriggerDevEndpointConfig(
+ name="schedules",
+ path="/api/v1/schedules",
+ pagination="page",
+ incremental_fields=[],
+ ),
+ # Queues report live counters (running / queued / paused) that only make sense as a current
+ # snapshot, and there is no timestamp to sync on, so full refresh each sync.
+ "queues": TriggerDevEndpointConfig(
+ name="queues",
+ path="/api/v1/queues",
+ pagination="page",
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(TRIGGER_DEV_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TRIGGER_DEV_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/source.py
index 1ca37a331bc9..664d2f149de7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/source.py
@@ -1,31 +1,176 @@
-from typing import cast
+from typing import Optional, cast
+from urllib.parse import urlsplit
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.mixins import _is_host_safe
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 TriggerDevSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ TRIGGER_DEV_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.trigger_dev import (
+ TriggerDevResumeConfig,
+ resolve_base_url,
+ trigger_dev_source,
+ validate_base_url,
+ validate_credentials as validate_trigger_dev_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TriggerDevSource(SimpleSource[TriggerDevSourceConfig]):
+class TriggerDevSource(ResumableSource[TriggerDevSourceConfig, TriggerDevResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TRIGGERDEV
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to whatever `base_url` points at, so retargeting it must re-require the
+ # secret — otherwise the preserved key could be exfiltrated to an attacker-controlled host.
+ return ["base_url"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.TRIGGER_DEV,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Trigger.dev",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Trigger.dev secret API key to sync your task run history into the PostHog Data warehouse.
+
+API keys are per environment (dev / staging / prod), so one connection syncs one environment. Copy the secret key for the environment you want from your [Trigger.dev project's API keys page](https://trigger.dev/docs/apikeys).
+""",
iconPath="/static/services/trigger_dev.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/trigger-dev",
keywords=["background jobs", "workflows", "task runs", "queues"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="tr_prod_...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="base_url",
+ label="API URL (self-hosted only)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://api.trigger.dev",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid, revoked, or wrong-environment secret key surfaces as a requests HTTPError
+ # when `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential
+ # problem, so stop the sync. The base host varies for self-hosted instances, so match on
+ # the stable status text only.
+ "401 Client Error": "Your Trigger.dev API key is invalid or has been revoked. Copy a valid secret key from your Trigger.dev project settings, then reconnect.",
+ "403 Client Error": "Your Trigger.dev API key does not have access to this data. Check the key's environment and permissions, then reconnect.",
+ "Invalid API key": "Your Trigger.dev API key is invalid or has been revoked. Copy a valid secret key from your Trigger.dev project settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: TriggerDevSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=TRIGGER_DEV_ENDPOINTS[endpoint].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: TriggerDevSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ base_url = resolve_base_url(config.base_url)
+ url_error = validate_base_url(base_url)
+ if url_error:
+ return False, url_error
+ host = urlsplit(base_url).hostname or ""
+ host_ok, host_error = _is_host_safe(host, team_id)
+ if not host_ok:
+ return False, host_error
+ return validate_trigger_dev_credentials(config.api_key, base_url)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TriggerDevResumeConfig]:
+ return ResumableSourceManager[TriggerDevResumeConfig](inputs, TriggerDevResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TriggerDevSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TriggerDevResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ base_url = resolve_base_url(config.base_url)
+ url_error = validate_base_url(base_url)
+ if url_error:
+ raise ValueError(url_error)
+ host = urlsplit(base_url).hostname or ""
+ host_ok, host_error = _is_host_safe(host, inputs.team_id)
+ if not host_ok:
+ raise ValueError(host_error or "Trigger.dev host is not allowed")
+
+ return trigger_dev_source(
+ api_key=config.api_key,
+ base_url=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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/tests/test_trigger_dev.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/tests/test_trigger_dev.py
new file mode 100644
index 000000000000..a9b6ca59695f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/tests/test_trigger_dev.py
@@ -0,0 +1,325 @@
+from datetime import UTC, date, datetime
+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.sources.trigger_dev import trigger_dev
+from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.trigger_dev import (
+ TriggerDevResumeConfig,
+ _format_incremental_value,
+ _should_stop_desc,
+ get_rows,
+ resolve_base_url,
+ trigger_dev_source,
+ validate_base_url,
+ validate_credentials,
+)
+
+BASE_URL = "https://api.trigger.dev"
+
+
+class _FakeManager:
+ def __init__(self, state: TriggerDevResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TriggerDevResumeConfig] = []
+ self.cleared = False
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TriggerDevResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TriggerDevResumeConfig) -> None:
+ self.saved.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared = True
+
+
+def _run_get_rows(
+ monkeypatch: Any,
+ endpoint: str,
+ responses: list[Any],
+ manager: _FakeManager | None = None,
+ **kwargs: Any,
+) -> tuple[list[dict], list[str], _FakeManager]:
+ fetched: list[str] = []
+ resp_iter = iter(responses)
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ fetched.append(url)
+ result = next(resp_iter)
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(trigger_dev, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(trigger_dev, "make_tracked_session", lambda *a, **k: MagicMock())
+
+ manager = manager or _FakeManager()
+ rows: list[dict] = []
+ for page in get_rows(
+ api_key="tr_prod_x",
+ base_url=BASE_URL,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(page)
+ return rows, fetched, manager
+
+
+class TestFormatIncrementalValue:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),
+ ("string_passthrough", "run_1234", "run_1234"),
+ ]
+ )
+ def test_format(self, _name: str, value: object, expected: str) -> None:
+ assert _format_incremental_value(value) == expected
+
+
+class TestResolveBaseUrl:
+ @parameterized.expand(
+ [
+ ("blank", None, "https://api.trigger.dev"),
+ ("empty", "", "https://api.trigger.dev"),
+ ("trailing_slash", "https://trigger.acme.internal/", "https://trigger.acme.internal"),
+ ("custom", "https://trigger.acme.dev", "https://trigger.acme.dev"),
+ ]
+ )
+ def test_resolve(self, _name: str, given: str | None, expected: str) -> None:
+ assert resolve_base_url(given) == expected
+
+
+class TestValidateBaseUrl:
+ @parameterized.expand(
+ [
+ ("default", "https://api.trigger.dev"),
+ ("self_hosted_https", "https://trigger.acme.dev"),
+ ]
+ )
+ def test_https_urls_pass(self, _name: str, base_url: str) -> None:
+ assert validate_base_url(base_url) is None
+
+ @parameterized.expand(
+ [
+ # Plaintext would send the secret bearer token in the clear.
+ ("http", "http://trigger.acme.dev"),
+ # `urlsplit` reads the host as example.com, but requests connects to 169.254.169.254.
+ ("backslash_authority_confusion", "https://169.254.169.254\\@example.com"),
+ ]
+ )
+ def test_unsafe_urls_are_rejected(self, _name: str, base_url: str) -> None:
+ assert validate_base_url(base_url) is not None
+
+
+class TestShouldStopDesc:
+ def test_no_cutoff_never_stops(self) -> None:
+ # First sync has no watermark; stopping early here would truncate the initial backfill.
+ items = [{"createdAt": "2020-01-01T00:00:00Z"}]
+ assert _should_stop_desc(items, "createdAt", None) is False
+
+ def test_stops_once_a_row_predates_cutoff(self) -> None:
+ cutoff = datetime(2026, 1, 7, tzinfo=UTC)
+ items = [{"createdAt": "2026-01-12T00:00:00Z"}, {"createdAt": "2026-01-02T00:00:00Z"}]
+ assert _should_stop_desc(items, "createdAt", cutoff) is True
+
+ def test_keeps_walking_while_page_is_newer_than_cutoff(self) -> None:
+ cutoff = datetime(2026, 1, 7, tzinfo=UTC)
+ items = [{"createdAt": "2026-01-12T00:00:00Z"}, {"createdAt": "2026-01-10T00:00:00Z"}]
+ assert _should_stop_desc(items, "createdAt", cutoff) is False
+
+
+class TestRunsCursorPagination:
+ def test_first_sync_sends_no_filter_and_walks_until_cursor_exhausted(self, monkeypatch: Any) -> None:
+ # No watermark => full backfill: no createdAt filter, follow pagination.next until it's null.
+ responses = [
+ {"data": [{"id": "r3"}, {"id": "r2"}], "pagination": {"next": "r2"}},
+ {"data": [{"id": "r1"}], "pagination": {"next": None}},
+ ]
+ rows, fetched, _ = _run_get_rows(
+ monkeypatch, "runs", responses, should_use_incremental_field=True, db_incremental_field_last_value=None
+ )
+ assert [r["id"] for r in rows] == ["r3", "r2", "r1"]
+ assert len(fetched) == 2
+ assert not any("filter" in url for url in fetched)
+ assert "page%5Bafter%5D=r2" in fetched[1]
+
+ def test_incremental_filters_first_page_then_stops_at_watermark(self, monkeypatch: Any) -> None:
+ # The createdAt filter is only sent on page one; later cursor pages must stop client-side once
+ # a page predates the watermark, or every incremental sync re-walks all history.
+ responses = [
+ {
+ "data": [
+ {"id": "r3", "createdAt": "2026-01-12T00:00:00Z"},
+ {"id": "r2", "createdAt": "2026-01-11T00:00:00Z"},
+ ],
+ "pagination": {"next": "r2"},
+ },
+ {
+ "data": [{"id": "r1", "createdAt": "2026-01-02T00:00:00Z"}],
+ "pagination": {"next": "r0"},
+ },
+ # Never fetched: the walk stops after the page containing r1 (older than the cutoff).
+ {"data": [{"id": "should_not_fetch"}], "pagination": {"next": None}},
+ ]
+ rows, fetched, _ = _run_get_rows(
+ monkeypatch,
+ "runs",
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),
+ )
+ assert [r["id"] for r in rows] == ["r3", "r2", "r1"]
+ assert len(fetched) == 2
+ assert "filter%5BcreatedAt%5D%5Bfrom%5D=" in fetched[0]
+ assert "filter" not in fetched[1]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeManager(TriggerDevResumeConfig(after="r5"))
+ responses = [{"data": [{"id": "r4"}], "pagination": {"next": None}}]
+ rows, fetched, _ = _run_get_rows(monkeypatch, "runs", responses, manager=manager)
+ assert [r["id"] for r in rows] == ["r4"]
+ assert "page%5Bafter%5D=r5" in fetched[0]
+
+ def test_checkpoints_current_page_cursor_after_yield(self, monkeypatch: Any) -> None:
+ # Resume must re-fetch the last yielded page (checkpoint the CURRENT cursor, not the next one)
+ # so a crash can't skip rows; merge dedupes the re-pulled page.
+ responses = [
+ {"data": [{"id": "r3"}], "pagination": {"next": "r2"}},
+ {"data": [{"id": "r1"}], "pagination": {"next": None}},
+ ]
+ _, _, manager = _run_get_rows(monkeypatch, "runs", responses)
+ assert [s.after for s in manager.saved] == [None, "r2"]
+
+ def test_clears_checkpoint_when_walk_completes(self, monkeypatch: Any) -> None:
+ # A finished walk must drop its checkpoint, or a later attempt resumes from the final page's
+ # cursor and skips every run created since (runs arrive newest-first, on page one).
+ responses = [{"data": [{"id": "r1"}], "pagination": {"next": None}}]
+ _, _, manager = _run_get_rows(monkeypatch, "runs", responses)
+ assert manager.cleared is True
+
+
+class TestClassicPagination:
+ def test_walks_pages_until_total_and_never_checkpoints(self, monkeypatch: Any) -> None:
+ # schedules/queues are small full-refresh tables: walk page/perPage to the last page and never
+ # save resume state (a restart just re-reads from page one).
+ responses = [
+ {"data": [{"id": "sched_1"}], "pagination": {"currentPage": 1, "totalPages": 2, "count": 2}},
+ {"data": [{"id": "sched_2"}], "pagination": {"currentPage": 2, "totalPages": 2, "count": 2}},
+ ]
+ rows, fetched, manager = _run_get_rows(monkeypatch, "schedules", responses)
+ assert [r["id"] for r in rows] == ["sched_1", "sched_2"]
+ assert "page=1" in fetched[0] and "page=2" in fetched[1]
+ assert manager.saved == []
+
+ def test_stops_on_empty_page(self, monkeypatch: Any) -> None:
+ responses = [{"data": [], "pagination": {"currentPage": 1, "totalPages": 5, "count": 0}}]
+ rows, fetched, _ = _run_get_rows(monkeypatch, "queues", responses)
+ assert rows == []
+ assert len(fetched) == 1
+
+ def test_bails_out_of_a_never_ending_pager(self, monkeypatch: Any) -> None:
+ # A page endpoint that keeps returning non-empty data with no totalPages must not loop forever.
+ responses = [{"data": [{"id": "q"}], "pagination": {}}] * (trigger_dev.MAX_CLASSIC_PAGES + 5)
+ _, fetched, _ = _run_get_rows(monkeypatch, "queues", responses)
+ assert len(fetched) == trigger_dev.MAX_CLASSIC_PAGES
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected_valid: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(trigger_dev, "make_tracked_session", return_value=session):
+ valid, error = validate_credentials("tr_prod_x", BASE_URL)
+ assert valid is expected_valid
+ assert (error is None) is expected_valid
+
+ def test_network_error_is_invalid_not_raised(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(trigger_dev, "make_tracked_session", return_value=session):
+ valid, error = validate_credentials("tr_prod_x", BASE_URL)
+ assert valid is False
+ assert error is not None
+
+
+class TestFetchPageRetries:
+ @parameterized.expand(
+ [
+ ("rate_limited", 429),
+ ("server_error", 503),
+ ]
+ )
+ def test_retryable_status_is_retried(self, _name: str, status_code: int) -> None:
+ bad = MagicMock()
+ bad.status_code = status_code
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"data": []}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(trigger_dev._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = trigger_dev._fetch_page(session, f"{BASE_URL}/api/v1/runs", {}, MagicMock())
+
+ assert result == {"data": []}
+ assert session.get.call_count == 2
+
+ def test_unauthorized_raises_and_is_not_retried(self) -> None:
+ response = MagicMock()
+ response.status_code = 401
+ response.ok = False
+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error: Unauthorized", response=response)
+ session = MagicMock()
+ session.get.return_value = response
+
+ with pytest.raises(requests.HTTPError):
+ trigger_dev._fetch_page(session, f"{BASE_URL}/api/v1/runs", {}, MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestSourceResponseSortMode:
+ @parameterized.expand([("runs", "desc"), ("schedules", "asc"), ("queues", "asc")])
+ def test_sort_mode_matches_arrival_order(self, endpoint: str, expected: str) -> None:
+ # Runs arrive newest-first; declaring asc there would corrupt the incremental watermark.
+ response = trigger_dev_source(
+ api_key="tr_prod_x",
+ base_url=BASE_URL,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.sort_mode == expected
+
+ def test_runs_partitioned_on_created_at(self, _name: str = "") -> None:
+ response = trigger_dev_source(
+ api_key="tr_prod_x",
+ base_url=BASE_URL,
+ endpoint="runs",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.partition_keys == ["createdAt"]
+ assert response.primary_keys == ["id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/tests/test_trigger_dev_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/tests/test_trigger_dev_source.py
new file mode 100644
index 000000000000..7c59353d47e9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/tests/test_trigger_dev_source.py
@@ -0,0 +1,163 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.source import TriggerDevSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.trigger_dev import (
+ TriggerDevResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestTriggerDevSourceConfig:
+ def test_source_type(self) -> None:
+ assert TriggerDevSource().source_type == ExternalDataSourceType.TRIGGERDEV
+
+ def test_fields_require_secret_api_key_and_optional_base_url(self) -> None:
+ fields = {f.name: f for f in TriggerDevSource().get_source_config.fields}
+ api_key, base_url = fields["api_key"], fields["base_url"]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert isinstance(base_url, SourceFieldInputConfig)
+ assert api_key.required is True
+ assert api_key.secret is True
+ assert base_url.required is False
+ assert base_url.secret is False
+
+ def test_base_url_is_a_connection_host_field(self) -> None:
+ # Retargeting base_url must re-require the secret, else the preserved key leaks to a new host.
+ assert TriggerDevSource().connection_host_fields == ["base_url"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog with no I/O, so public docs can render the table list.
+ assert TriggerDevSource.lists_tables_without_credentials is True
+
+
+class TestTriggerDevSchemas:
+ def test_runs_is_incremental_and_config_endpoints_are_full_refresh(self) -> None:
+ schemas = {s.name: s for s in TriggerDevSource().get_schemas(MagicMock(), team_id=1)}
+ assert set(schemas) == {"runs", "schedules", "queues"}
+ assert schemas["runs"].supports_incremental is True
+ assert [f["field"] for f in schemas["runs"].incremental_fields] == ["createdAt"]
+ assert schemas["schedules"].supports_incremental is False
+ assert schemas["queues"].supports_incremental is False
+
+ def test_names_filter(self) -> None:
+ schemas = TriggerDevSource().get_schemas(MagicMock(), team_id=1, names=["queues"])
+ assert [s.name for s in schemas] == ["queues"]
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.trigger.dev/api/v1/runs"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.trigger.dev/api/v1/schedules"),
+ ("invalid_body", "Invalid API key"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ errors = TriggerDevSource().get_non_retryable_errors()
+ assert any(key in observed for key in errors)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.trigger.dev', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:
+ errors = TriggerDevSource().get_non_retryable_errors()
+ assert not any(key in observed for key in errors)
+
+
+class TestValidateCredentials:
+ def test_blocks_unsafe_host_before_probing(self) -> None:
+ # An internal/private base_url must be rejected without an outbound request being made.
+ config = MagicMock(api_key="tr_prod_x", base_url="https://169.254.169.254")
+ with (
+ patch.object(source_module, "_is_host_safe", return_value=(False, "internal IP blocked")) as host_check,
+ patch.object(source_module, "validate_trigger_dev_credentials") as probe,
+ ):
+ valid, error = TriggerDevSource().validate_credentials(config, team_id=1)
+ assert valid is False
+ assert error == "internal IP blocked"
+ host_check.assert_called_once()
+ probe.assert_not_called()
+
+ def test_rejects_plaintext_base_url_before_probing(self) -> None:
+ # A non-HTTPS URL would leak the bearer token; reject it without any outbound request.
+ config = MagicMock(api_key="tr_prod_x", base_url="http://trigger.acme.dev")
+ with patch.object(source_module, "validate_trigger_dev_credentials") as probe:
+ valid, error = TriggerDevSource().validate_credentials(config, team_id=1)
+ assert valid is False
+ assert error is not None
+ probe.assert_not_called()
+
+ def test_delegates_to_transport_when_host_is_safe(self) -> None:
+ config = MagicMock(api_key="tr_prod_x", base_url=None)
+ with (
+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),
+ patch.object(source_module, "validate_trigger_dev_credentials", return_value=(True, None)) as probe,
+ ):
+ valid, error = TriggerDevSource().validate_credentials(config, team_id=1)
+ assert valid is True
+ assert error is None
+ # Blank base_url resolves to the hosted API URL before probing.
+ probe.assert_called_once_with("tr_prod_x", "https://api.trigger.dev")
+
+
+class TestSourceForPipeline:
+ def test_plumbs_resolved_base_url_and_incremental_inputs(self) -> None:
+ config = MagicMock(api_key="tr_prod_x", base_url="https://trigger.acme.dev/")
+ inputs = MagicMock(
+ schema_name="runs",
+ team_id=1,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="createdAt",
+ )
+ with (
+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),
+ patch.object(source_module, "trigger_dev_source", return_value="SENTINEL") as build,
+ ):
+ result = TriggerDevSource().source_for_pipeline(config, MagicMock(), inputs)
+ assert result is build.return_value
+ kwargs = build.call_args.kwargs
+ assert kwargs["base_url"] == "https://trigger.acme.dev"
+ assert kwargs["endpoint"] == "runs"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ def test_does_not_pass_watermark_when_not_incremental(self) -> None:
+ config = MagicMock(api_key="tr_prod_x", base_url=None)
+ inputs = MagicMock(
+ schema_name="schedules",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field=None,
+ )
+ with (
+ patch.object(source_module, "_is_host_safe", return_value=(True, None)),
+ patch.object(source_module, "trigger_dev_source", return_value="SENTINEL") as build,
+ ):
+ TriggerDevSource().source_for_pipeline(config, MagicMock(), inputs)
+ assert build.call_args.kwargs["db_incremental_field_last_value"] is None
+
+
+class TestResumableSourceManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = TriggerDevSource().get_resumable_source_manager(inputs)
+ assert manager._data_class is TriggerDevResumeConfig
+
+
+class TestGetDocumentedTables:
+ def test_publishes_runs_table_with_canonical_description(self) -> None:
+ tables = {t["name"]: t for t in TriggerDevSource().get_documented_tables()}
+ assert set(tables) == {"runs", "schedules", "queues"}
+ assert "execution" in tables["runs"]["description"].lower()
+ assert "Incremental" in tables["runs"]["sync_methods"]
+ assert tables["schedules"]["sync_methods"] == ["Full refresh"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/trigger_dev.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/trigger_dev.py
new file mode 100644
index 000000000000..dd5443da813a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trigger_dev/trigger_dev.py
@@ -0,0 +1,323 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode, urlsplit
+
+import requests
+from dateutil import parser as dateutil_parser
+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.trigger_dev.settings import (
+ TRIGGER_DEV_ENDPOINTS,
+ TriggerDevEndpointConfig,
+)
+
+TRIGGER_DEV_DEFAULT_BASE_URL = "https://api.trigger.dev"
+
+# Runaway guard for classic page/perPage pagination: an API that returns non-empty pages without a
+# `totalPages` (or that ignores the `page` param entirely) would otherwise loop until the activity
+# times out. Schedules and queues are small config tables, so this ceiling is far above any real size.
+MAX_CLASSIC_PAGES = 10_000
+
+
+class TriggerDevRetryableError(Exception):
+ pass
+
+
+class TriggerDevResumeConfig:
+ # The page[after] cursor used to FETCH the page we last yielded. `None` means the first page.
+ # We checkpoint the current page's cursor (not the next one) so a crash re-fetches and re-yields
+ # the last page rather than skipping it; merge dedupes the re-pulled rows on the primary key.
+ after: str | None = None
+
+
+def resolve_base_url(base_url: str | None) -> str:
+ """Cloud users leave this blank (api.trigger.dev); self-hosters point it at their instance."""
+ resolved = (base_url or "").strip().rstrip("/")
+ return resolved or TRIGGER_DEV_DEFAULT_BASE_URL
+
+
+def validate_base_url(base_url: str) -> str | None:
+ """Return an error message if `base_url` is not a safe HTTPS URL, else None.
+
+ Defense-in-depth on top of the Smokescreen egress proxy. The secret API key is sent as a bearer
+ token to whatever this points at, so we:
+ - require HTTPS, so the key is never sent over plaintext HTTP;
+ - reject backslashes, which `urlsplit` folds into the userinfo (host `example.com` for
+ `https://169.254.169.254\\@example.com`) while `requests`/`urllib3` treat them as `/` and
+ connect to `169.254.169.254`, letting a crafted URL slip past the hostname safety check.
+ """
+ if "\\" in base_url:
+ return "The Trigger.dev API URL must not contain backslashes."
+ if urlsplit(base_url).scheme.lower() != "https":
+ return "The Trigger.dev API URL must use HTTPS."
+ return None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _format_incremental_value(value: Any) -> str:
+ """Format an incremental cursor value as an ISO 8601 string for the createdAt filter."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.isoformat()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()
+ return str(value)
+
+
+def _as_utc(dt: datetime) -> datetime:
+ return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+
+
+def _is_older_than_cutoff(value: Any, cutoff: datetime) -> bool:
+ """True when `value` (an ISO 8601 string or datetime) is at/older than `cutoff`."""
+ if value is None:
+ return False
+ if isinstance(value, str):
+ try:
+ parsed = dateutil_parser.parse(value)
+ except (ValueError, TypeError, OverflowError):
+ return False
+ elif isinstance(value, datetime):
+ parsed = value
+ else:
+ return False
+ return _as_utc(parsed) <= _as_utc(cutoff)
+
+
+def _should_stop_desc(items: list[dict[str, Any]], incremental_field: str | None, cutoff: datetime | None) -> bool:
+ """Desc incremental can stop the moment a page contains a row at/older than the cutoff.
+
+ The runs endpoint applies the createdAt filter only on the first (uncursored) request; later
+ cursor pages walk back through history unbounded, so the paginator must stop client-side once an
+ entire page predates the watermark. Without this, every incremental sync would re-walk all
+ history down to the first run.
+ """
+ if not incremental_field or cutoff is None or not items:
+ return False
+ return any(_is_older_than_cutoff(item.get(incremental_field), cutoff) for item in items if item)
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ TriggerDevRetryableError,
+ 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], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # Trigger.dev rate-limits per API key with a token bucket and standard x-ratelimit-* headers;
+ # back off and retry on 429 and transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise TriggerDevRetryableError(f"Trigger.dev API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Trigger.dev API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{base_url}{path}"
+ return f"{base_url}{path}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str, base_url: str) -> tuple[bool, str | None]:
+ """Probe the token by listing one page of runs. 200 => valid; 401/403 => bad token."""
+ # page[size] minimum is 10; the smallest cheap probe the runs endpoint allows.
+ url = _build_url(base_url, TRIGGER_DEV_ENDPOINTS["runs"].path, {"page[size]": 10})
+ try:
+ # allow_redirects=False keeps the bearer token pinned to the validated host: a 30x from a
+ # self-hosted instance must not replay `Authorization` to an internal or attacker origin.
+ response = make_tracked_session(allow_redirects=False).get(url, headers=_get_headers(api_key), 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 Trigger.dev API key. Copy the secret key for the environment you want to sync."
+ return False, f"Trigger.dev returned an unexpected response: {response.status_code}"
+
+
+def _iter_cursor_pages(
+ session: requests.Session,
+ base_url: str,
+ headers: dict[str, str],
+ config: TriggerDevEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TriggerDevResumeConfig],
+ incremental_field: str | None,
+ cutoff: datetime | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the runs endpoint newest-first via page[after], yielding one list of rows per page."""
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ after: str | None = resume.after if resume else None
+ formatted_cutoff = _format_incremental_value(cutoff) if cutoff is not None else None
+
+ while True:
+ params: dict[str, Any] = {"page[size]": config.page_size}
+ if after is None:
+ # The createdAt filter is only sent on the first (uncursored) request. Mixing a time
+ # filter with the cursor is unverified against the live API (no credentials at build
+ # time), so we scope it to page one and bound the rest client-side via _should_stop_desc.
+ if formatted_cutoff is not None:
+ params["filter[createdAt][from]"] = formatted_cutoff
+ else:
+ params["page[after]"] = after
+
+ url = _build_url(base_url, config.path, params)
+ data = _fetch_page(session, url, headers, logger)
+
+ items = data.get("data", []) or []
+ next_after = (data.get("pagination", {}) or {}).get("next")
+ stop = _should_stop_desc(items, incremental_field, cutoff)
+
+ yield items
+ # Checkpoint the CURRENT page's cursor after yielding, so a crash re-fetches this page.
+ resumable_source_manager.save_state(TriggerDevResumeConfig(after=after))
+
+ if stop or not next_after:
+ break
+ after = next_after
+
+ # The walk finished cleanly, so drop the checkpoint. Otherwise a later attempt (e.g. a retry that
+ # re-runs extract after the previous one completed) would resume from the final page's cursor and
+ # skip every run created since — runs arrive newest-first, so the new ones live on page one.
+ resumable_source_manager.clear_state()
+
+
+def _iter_classic_pages(
+ session: requests.Session,
+ base_url: str,
+ headers: dict[str, str],
+ config: TriggerDevEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk a classic page/perPage endpoint (schedules, queues), yielding one list of rows per page.
+
+ These are small full-refresh tables, so we don't checkpoint resume state: a worker restart
+ simply re-reads from page one.
+ """
+ page = 1
+ while page <= MAX_CLASSIC_PAGES:
+ url = _build_url(base_url, config.path, {"page": page, "perPage": config.page_size})
+ data = _fetch_page(session, url, headers, logger)
+
+ items = data.get("data", []) or []
+ yield items
+
+ pagination = data.get("pagination", {}) or {}
+ total_pages = pagination.get("totalPages")
+ if not items:
+ break
+ if total_pages is not None and page >= total_pages:
+ break
+ page += 1
+ else:
+ # Ran out of the safety budget without a natural stop: the API is paging forever (no
+ # totalPages and never an empty page). Bail loudly rather than spin until the activity dies.
+ logger.error(
+ f"Trigger.dev classic pagination exceeded {MAX_CLASSIC_PAGES} pages for {config.name}; stopping to avoid an unbounded loop."
+ )
+
+
+def get_rows(
+ api_key: str,
+ base_url: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TriggerDevResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = TRIGGER_DEV_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # allow_redirects=False keeps the bearer token pinned to the validated host across every page.
+ session = make_tracked_session(allow_redirects=False)
+
+ if config.pagination == "cursor":
+ cutoff: datetime | None = None
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ value = db_incremental_field_last_value
+ if not isinstance(value, datetime):
+ # The framework hands us a datetime for DateTime incremental fields; guard anyway so a
+ # stringified watermark still bounds the walk rather than crashing.
+ try:
+ value = dateutil_parser.parse(str(value))
+ except (ValueError, TypeError, OverflowError):
+ value = None
+ if isinstance(value, datetime):
+ cutoff = _as_utc(value) - (config.incremental_lookback or timedelta(0))
+ yield from _iter_cursor_pages(
+ session,
+ base_url,
+ headers,
+ config,
+ logger,
+ resumable_source_manager,
+ incremental_field or config.default_incremental_field,
+ cutoff,
+ )
+ return
+
+ yield from _iter_classic_pages(session, base_url, headers, config, logger)
+
+
+def trigger_dev_source(
+ api_key: str,
+ base_url: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TriggerDevResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = TRIGGER_DEV_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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Runs arrive newest-first; the pipeline must know so it defers the incremental watermark
+ # correctly. Classic full-refresh endpoints keep the default asc.
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )