:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add 4 missing tables to the TriggerDev source (#119111)
Tom Owers3d46f4a80440
diff --git a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txtindex 254f1c2a1081..bff693f0d231 100644--- a/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt+++ b/posthog/test/repo_invariants/resume_state_after_yield_baseline.txt@@ -389,7 +389,6 @@ terraform_cloud/terraform_cloud.py::_get_fan_out_rowsterraform_cloud/terraform_cloud.py::_get_top_level_rowstransistor/transistor.py::get_rowstravis_ci/travis_ci.py::get_rows-trigger_dev/trigger_dev.py::_iter_cursor_pagestrunk_io/trunk_io.py::failing_teststwelve_data/twelve_data.py::twelve_data_rowsubidots/ubidots.py::get_rowsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex ae09148bb384..e690ebeace22 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -12463,10 +12463,10 @@ Today (3): `queues`, `runs`, `schedules`Diffed against: <https://trigger.dev/docs/llms.txt>-- [ ] `errors (list error groups)` — failed runs grouped by fingerprint with lifecycle state; the headline reliability metric (high)-- [ ] `deployments (list)` — deploy history and worker versions, the dimension that explains run behavior changes (high)-- [ ] `runs/{id}/events` — OTel span events per run; the step-level detail behind a run's duration and failure (medium)-- [ ] `waitpoints/tokens (list)` — waitpoint tokens and their completion state, showing where runs block on external systems (medium)+- [x] `errors (list error groups)` — failed runs grouped by fingerprint with lifecycle state; the headline reliability metric (high)+- [x] `deployments (list)` — deploy history and worker versions, the dimension that explains run behavior changes (high)+- [x] `runs/{id}/events` — OTel span events per run; the step-level detail behind a run's duration and failure (medium)+- [x] `waitpoints/tokens (list)` — waitpoint tokens and their completion state, showing where runs block on external systems (medium)- [ ] `sessions (list)` — durable session records tying multiple runs to one external identity (medium)- [ ] `bulk-actions (list)` — bulk cancel/replay operations and their processing counts (low)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.pyindex 102c3b3cee79..5edb53f7bcae 100644--- 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@@ -57,4 +57,77 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"concurrency": "Detailed concurrency info (current effective limit, base limit, and any override).",},},+ "errors": {+ "description": "A group of failed runs that share an error fingerprint within one task, with its lifecycle state.",+ "docs_url": "https://trigger.dev/docs/management/errors/list",+ "columns": {+ "id": "Identifier of the error group, prefixed with `error_` and derived from the fingerprint.",+ "fingerprint": "The raw fingerprint the error is grouped by, derived from the error type, message and stack trace.",+ "taskIdentifier": "Identifier of the task that the error belongs to.",+ "errorType": "The error type or name (e.g. TypeError).",+ "errorMessage": "The normalized error message.",+ "status": "Lifecycle status of the error group: unresolved, resolved, or ignored.",+ "count": "Number of occurrences within the plan's log retention window at sync time.",+ "firstSeen": "When the error group was first seen.",+ "lastSeen": "When the error group was last seen.",+ "resolvedAt": "When the error group was marked as resolved, if it was.",+ "ignoredUntil": "When an ignored error group surfaces again, if it was ignored for a fixed window.",+ },+ },+ "deployments": {+ "description": "A deployment of the project's tasks to the environment, with its worker version and status.",+ "docs_url": "https://trigger.dev/docs/management/deployments/list",+ "columns": {+ "id": "Unique identifier for the deployment.",+ "createdAt": "When the deployment was created.",+ "shortCode": "Short code for the deployment.",+ "version": "Worker version that the deployment created (e.g. 20250228.1).",+ "runtime": "Runtime the deployment uses (e.g. node).",+ "runtimeVersion": "Version of the runtime.",+ "status": "Current status: PENDING, BUILDING, DEPLOYING, DEPLOYED, FAILED, CANCELED, or TIMED_OUT.",+ "deployedAt": "When the deployment was promoted to DEPLOYED.",+ "git": "Git metadata associated with the deployment.",+ "error": "Error data if the deployment failed.",+ "externalId": "External deployment id used by version skew protection to pin runs, if set.",+ },+ },+ "waitpoint_tokens": {+ "description": "A waitpoint token that pauses a run until an external system or a person completes it.",+ "docs_url": "https://trigger.dev/docs/management/waitpoints/list",+ "columns": {+ "id": "Unique identifier for the waitpoint token, prefixed with `waitpoint_`.",+ "status": "Current status of the token: WAITING, COMPLETED, or TIMED_OUT.",+ "idempotencyKey": "Idempotency key used when the token was created, if any.",+ "idempotencyKeyExpiresAt": "When the idempotency key expires.",+ "timeoutAt": "When the token times out, if a timeout was set.",+ "completedAt": "When the token was completed, if it was.",+ "output": "Serialized output passed when the token was completed.",+ "outputType": "Content type of the output (e.g. application/json).",+ "outputIsError": "Whether the output represents an error, such as a timeout.",+ "tags": "Tags attached to the waitpoint.",+ "createdAt": "When the waitpoint token was created.",+ },+ },+ "run_events": {+ "description": "An OpenTelemetry span or log event recorded during a run.",+ "docs_url": "https://trigger.dev/docs/management/runs/retrieve-events",+ "columns": {+ "_runs_id": "Identifier of the run that the events were fetched for.",+ "_runs_createdAt": "When that run was created.",+ "spanId": "Span ID of the event.",+ "parentId": "Parent span ID, if any.",+ "runId": "Run ID associated with the event.",+ "message": "The event message.",+ "startTime": "Start time of the event, in nanoseconds since the epoch.",+ "duration": "Duration of the event, in nanoseconds.",+ "isError": "Whether the event represents an error.",+ "isPartial": "Whether the event was still in progress when it was synced.",+ "isCancelled": "Whether the event was cancelled.",+ "level": "Log level of the event: TRACE, DEBUG, LOG, INFO, WARN, or ERROR.",+ "kind": "Kind of span event (e.g. INTERNAL, SERVER, CLIENT, LOG).",+ "attemptNumber": "Attempt number that the event belongs to.",+ "taskSlug": "Identifier of the task.",+ "events": "Span events, such as exceptions or cancellations, that occurred during this event.",+ },+ },}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.pyindex 161ccaa69720..9199b832cbf7 100644--- 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@@ -5,14 +5,15 @@ from typing import Literal, Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-@dataclass+@dataclass # nosemgrep: prefer-frozen-dataclasses -- pre-existing; new field shifts the backlog finding into diffclass TriggerDevEndpointConfig:name: strpath: strincremental_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"+ # "cursor" -> page[after]/pagination.next cursor pagination (runs, errors, deployments, waitpoints).+ # "page" -> classic page/perPage pagination (schedules, queues).+ # "run_fanout" -> one request per run, walking the runs endpoint as the parent.+ pagination: Literal["cursor", "page", "run_fanout"] = "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.@@ -26,6 +27,11 @@ class TriggerDevEndpointConfig:# 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+ # Query param that takes the created-at lower bound on the first cursor page.+ created_from_param: Optional[str] = None+ extra_params: dict[str, str] = field(default_factory=dict)+ # Fields dropped from every row before it is yielded.+ excluded_fields: tuple[str, ...] = ()TRIGGER_DEV_ENDPOINTS: dict[str, TriggerDevEndpointConfig] = {@@ -42,6 +48,7 @@ TRIGGER_DEV_ENDPOINTS: dict[str, TriggerDevEndpointConfig] = {partition_key="createdAt",sort_mode="desc",incremental_lookback=timedelta(days=3),+ created_from_param="filter[createdAt][from]",incremental_fields=[{"label": "createdAt",@@ -67,6 +74,84 @@ TRIGGER_DEV_ENDPOINTS: dict[str, TriggerDevEndpointConfig] = {pagination="page",incremental_fields=[],),+ # Error groups: failed runs grouped by fingerprint per task. Ordered by occurrence count with no+ # creation filter, and status / count / lastSeen keep changing, so full refresh each sync. The API+ # counts occurrences over the last day by default; the wide period asks for every group in the+ # plan's log retention, which the server clamps to silently.+ "errors": TriggerDevEndpointConfig(+ name="errors",+ path="/api/v1/errors",+ pagination="cursor",+ partition_key="firstSeen",+ extra_params={"filter[period]": "365d"},+ # The id is derived from the fingerprint alone, and the same fingerprint can group per task.+ primary_keys=["id", "taskIdentifier"],+ incremental_fields=[],+ ),+ # Deployments arrive newest-first. Status moves from BUILDING to DEPLOYED / FAILED / TIMED_OUT+ # within hours, so a one-day lookback re-reads deployments that were still in progress.+ "deployments": TriggerDevEndpointConfig(+ name="deployments",+ path="/api/v1/deployments",+ pagination="cursor",+ default_incremental_field="createdAt",+ partition_key="createdAt",+ sort_mode="desc",+ incremental_lookback=timedelta(days=1),+ created_from_param="from",+ incremental_fields=[+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Waitpoint tokens arrive newest-first. A token can wait on a person or an external system for+ # days, so the lookback is wider than for runs to pick up late completions.+ "waitpoint_tokens": TriggerDevEndpointConfig(+ name="waitpoint_tokens",+ path="/api/v1/waitpoints/tokens",+ pagination="cursor",+ default_incremental_field="createdAt",+ partition_key="createdAt",+ sort_mode="desc",+ incremental_lookback=timedelta(days=7),+ created_from_param="filter[createdAt][from]",+ # The callback URL completes the token without an API key, so it must not land in the warehouse.+ excluded_fields=("url",),+ incremental_fields=[+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # OTel span events per run, fetched once per run while walking the runs endpoint newest-first.+ # Each row carries the parent run's id and createdAt, so the sync is incremental on the parent's+ # creation time with the same lookback as runs. Off by default: it costs one request per run.+ "run_events": TriggerDevEndpointConfig(+ name="run_events",+ path="/api/v1/runs/{run_id}/events",+ pagination="run_fanout",+ default_incremental_field="_runs_createdAt",+ partition_key="_runs_createdAt",+ sort_mode="desc",+ incremental_lookback=timedelta(days=3),+ primary_keys=["_runs_id", "spanId"],+ should_sync_default=False,+ incremental_fields=[+ {+ "label": "_runs_createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "_runs_createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),}ENDPOINTS = tuple(TRIGGER_DEV_ENDPOINTS.keys())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.pyindex f7a26e046549..bc86f6a51560 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@@ -124,10 +124,12 @@ API keys are per environment (dev / staging / prod), so one connection syncs one) -> list[SourceSchema]:def _build_schema(endpoint: str) -> SourceSchema:has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ # A lookback re-reads rows that are already stored, and append would duplicate them.+ lookback = TRIGGER_DEV_ENDPOINTS[endpoint].incremental_lookbackreturn SourceSchema(name=endpoint,supports_incremental=has_incremental,- supports_append=has_incremental,+ supports_append=has_incremental and lookback is None,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),should_sync_default=TRIGGER_DEV_ENDPOINTS[endpoint].should_sync_default,)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.pyindex 2ecc37e7afbf..1103f77dca66 100644--- 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@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev import trigger_devfrom products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.source import TriggerDevSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.trigger_dev.trigger_dev import (+ TriggerDevResumeConfig,_format_incremental_value,_should_stop_desc,resolve_base_url,@@ -96,7 +97,14 @@ class TestShouldStopDesc:class TestRunsCursorPagination:- def test_incremental_filters_first_page_then_stops_at_watermark(self) -> None:+ @parameterized.expand(+ [+ ("runs", "filter[createdAt][from]"),+ ("deployments", "from"),+ ("waitpoint_tokens", "filter[createdAt][from]"),+ ]+ )+ def test_incremental_filters_first_page_then_stops_at_watermark(self, endpoint: str, filter_param: str) -> 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 = [@@ -119,25 +127,149 @@ class TestRunsCursorPagination:_json({"data": [{"id": "should_not_fetch"}], "pagination": {"next": None}}),]result = _run(- "runs",+ endpoint,responses,should_use_incremental_field=True,db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),)assert [r["id"] for r in result.rows] == ["r3", "r2", "r1"]assert len(result.requests) == 2- assert result.requests[0].param("filter[createdAt][from]") is not None- assert not any(name.startswith("filter") for name in result.requests[1].query)+ assert result.requests[0].param(filter_param) is not None+ assert filter_param not in result.requests[1].query- def test_checkpoints_current_page_cursor_after_yield(self) -> 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.+ def test_errors_send_the_wide_period_on_every_page(self) -> None:+ # Without the period the API counts only the last day, so most error groups would be missing.+ responses = [+ _json({"data": [{"id": "error_a", "taskIdentifier": "t1"}], "pagination": {"next": "c1"}}),+ _json({"data": [{"id": "error_a", "taskIdentifier": "t2"}], "pagination": {}}),+ ]+ result = _run("errors", responses)+ assert [(r["id"], r["taskIdentifier"]) for r in result.rows] == [("error_a", "t1"), ("error_a", "t2")]+ assert result.params("filter[period]") == ["365d", "365d"]+ assert result.requests[1].param("page[after]") == "c1"++ def test_waitpoint_tokens_drop_the_callback_url(self) -> None:+ # The callback URL completes the token without an API key, so it must never reach the warehouse.+ token = {+ "id": "waitpoint_1",+ "status": "WAITING",+ "url": "https://api.trigger.dev/api/v1/waitpoints/tokens/waitpoint_1/callback/fakehash",+ "createdAt": "2026-01-12T00:00:00Z",+ }+ result = _run("waitpoint_tokens", [_json({"data": [token], "pagination": {}})])+ assert result.rows == [{"id": "waitpoint_1", "status": "WAITING", "createdAt": "2026-01-12T00:00:00Z"}]++ def test_stages_next_page_cursor_before_each_yield(self) -> None:+ # A resumed full refresh appends without merging, so the state must point at the first unread+ # page: staging the current cursor would replay a page that was already written.responses = [_json({"data": [{"id": "r3"}], "pagination": {"next": "r2"}}),_json({"data": [{"id": "r1"}], "pagination": {"next": None}}),]- result = _run("runs", responses)- assert [s.after for s in result.saved_states] == [None, "r2"]+ result = _run("errors", responses)+ assert [s.after for s in result.saved_states] == ["r2"]+++class TestRunEventsFanOut:+ def test_fetches_events_per_run_across_run_pages(self) -> None:+ responses = [+ _json(+ {+ "data": [+ {"id": "run_b", "createdAt": "2026-01-12T00:00:00Z"},+ {"id": "run_gone", "createdAt": "2026-01-11T12:00:00Z"},+ {"id": "run_quiet", "createdAt": "2026-01-11T06:00:00Z"},+ ],+ "pagination": {"next": "run_quiet"},+ }+ ),+ _json({"events": [{"spanId": "s1"}, {"spanId": "s2"}]}),+ # A run deleted after the runs page was read is skipped, not fatal.+ ScriptedResponse(status=404, json={"error": "Run not found"}),+ _json({"events": []}),+ _json({"data": [{"id": "run_a", "createdAt": "2026-01-10T00:00:00Z"}], "pagination": {}}),+ _json({"events": [{"spanId": "s1"}]}),+ ]+ result = _run("run_events", responses)+ assert [(r["_runs_id"], r["spanId"], r["_runs_createdAt"]) for r in result.rows] == [+ ("run_b", "s1", "2026-01-12T00:00:00Z"),+ ("run_b", "s2", "2026-01-12T00:00:00Z"),+ ("run_a", "s1", "2026-01-10T00:00:00Z"),+ ]+ assert [r.path for r in result.requests] == [+ "/api/v1/runs",+ "/api/v1/runs/run_b/events",+ "/api/v1/runs/run_gone/events",+ "/api/v1/runs/run_quiet/events",+ "/api/v1/runs",+ "/api/v1/runs/run_a/events",+ ]+ assert result.requests[4].param("page[after]") == "run_quiet"++ def test_stages_the_run_before_its_events_and_resumes_after_it(self) -> None:+ # A full refresh appends without merging, so a resume must not replay the events of a run+ # that was already written, even when it is in the middle of a runs page.+ runs_page = {+ "data": [+ {"id": "run_b", "createdAt": "2026-01-12T00:00:00Z"},+ {"id": "run_a", "createdAt": "2026-01-11T00:00:00Z"},+ ],+ "pagination": {},+ }+ events = _json({"events": [{"spanId": "s1"}]})+ fresh = _run("run_events", [_json(runs_page), events, events])+ assert [(s.after, s.last_run_id) for s in fresh.saved_states] == [(None, "run_b"), (None, "run_a")]++ resumed = _run(+ "run_events",+ [_json(runs_page), _json({"events": [{"spanId": "s9"}]})],+ resume_state=TriggerDevResumeConfig(after=None, last_run_id="run_b"),+ )+ assert [(r["_runs_id"], r["spanId"]) for r in resumed.rows] == [("run_a", "s9")]+ assert [r.path for r in resumed.requests] == ["/api/v1/runs", "/api/v1/runs/run_a/events"]++ def test_resume_skips_newer_runs_when_the_checkpointed_run_was_deleted(self) -> None:+ # Without the marker run, the createdAt boundary keeps the newer, already written runs out.+ runs_page = {+ "data": [+ {"id": "run_c", "createdAt": "2026-01-12T00:00:00Z"},+ {"id": "run_a", "createdAt": "2026-01-10T00:00:00Z"},+ ],+ "pagination": {},+ }+ resumed = _run(+ "run_events",+ [_json(runs_page), _json({"events": [{"spanId": "s9"}]})],+ resume_state=TriggerDevResumeConfig(+ after=None, last_run_id="run_b", last_run_created_at="2026-01-11T00:00:00Z"+ ),+ )+ assert [r["_runs_id"] for r in resumed.rows] == ["run_a"]+ assert [r.path for r in resumed.requests] == ["/api/v1/runs", "/api/v1/runs/run_a/events"]++ def test_runs_before_the_cutoff_cost_no_events_request(self) -> None:+ # The page that crosses the watermark still lists older runs. They were synced before, and each+ # one would cost a request.+ runs_page = {+ "data": [+ {"id": "run_new", "createdAt": "2026-01-12T00:00:00Z"},+ {"id": "run_old", "createdAt": "2026-01-05T00:00:00Z"},+ ],+ "pagination": {"next": "run_old"},+ }+ result = _run(+ "run_events",+ [_json(runs_page), _json({"events": [{"spanId": "s1"}]})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 10, tzinfo=UTC),+ )+ assert [r["_runs_id"] for r in result.rows] == ["run_new"]+ assert [r.path for r in result.requests] == ["/api/v1/runs", "/api/v1/runs/run_new/events"]++ def test_runs_without_events_are_staged_so_a_resume_skips_them(self) -> None:+ runs_page = {"data": [{"id": "run_quiet", "createdAt": "2026-01-12T00:00:00Z"}], "pagination": {}}+ result = _run("run_events", [_json(runs_page), _json({"events": []})])+ assert [s.last_run_id for s in result.saved_states] == ["run_quiet"]class TestClassicPagination:@@ -224,9 +356,27 @@ class TestFetchPageRetries:class TestSourceResponseSortMode:- @parameterized.expand([("runs", "desc"), ("schedules", "asc"), ("queues", "asc")])+ @parameterized.expand(+ [+ ("runs", "desc"),+ ("deployments", "desc"),+ ("waitpoint_tokens", "desc"),+ ("run_events", "desc"),+ ("errors", "asc"),+ ("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 = _run(endpoint, []).responseassert response is not Noneassert response.sort_mode == expected+++class TestSampleCapture:+ @parameterized.expand([("runs", True), ("waitpoint_tokens", False)])+ def test_capture_is_off_when_a_field_is_excluded(self, endpoint: str, expected: bool) -> None:+ # HTTP samples are stored before excluded_fields is applied, so the callback URL would leak.+ result = _run(endpoint, [_json({"data": [], "pagination": {}})])+ assert result.session_options[0]["capture"] is expecteddiff --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.pyindex 43b0e365182d..dba6122ff4ba 100644--- 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@@ -29,12 +29,14 @@ class TriggerDevRetryableError(Exception):pass[email protected] # nosemgrep: prefer-frozen-dataclasses -- pre-existing; new field shifts the backlog finding into diffclass 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.+ # The page[after] cursor of the page to fetch on resume. `None` means the first page.after: str | None = None+ # Only the run fan-out sets this: the runs of the page at `after` up to and including this one are done.+ last_run_id: str | None = None+ # That run's createdAt, the fallback boundary when the run no longer exists on the page.+ last_run_created_at: str | None = Nonedef resolve_base_url(base_url: str | None) -> str:@@ -162,6 +164,34 @@ def validate_credentials(api_key: str, base_url: str) -> tuple[bool, str | None]return False, f"Trigger.dev returned an unexpected response: {response.status_code}"+def _fetch_cursor_page(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ config: TriggerDevEndpointConfig,+ logger: FilteringBoundLogger,+ after: str | None,+ formatted_cutoff: str | None,+) -> tuple[list[dict[str, Any]], str | None]:+ """Fetch one page of a cursor endpoint, returning its rows and the cursor of the next page."""+ params: dict[str, Any] = {"page[size]": config.page_size, **config.extra_params}+ 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 and config.created_from_param:+ params[config.created_from_param] = formatted_cutoff+ else:+ params["page[after]"] = after++ data = _fetch_page(session, _build_url(base_url, config.path, params), headers, logger)++ items = data.get("data", []) or []+ if config.excluded_fields:+ items = [{k: v for k, v in item.items() if k not in config.excluded_fields} for item in items]+ return items, (data.get("pagination", {}) or {}).get("next")++def _iter_cursor_pages(session: requests.Session,base_url: str,@@ -172,32 +202,22 @@ def _iter_cursor_pages(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."""+ """Walk a cursor endpoint newest-first via page[after], yielding one list of rows per page.++ The resume state is the next unread page, staged before the yield it covers, so a resumed full+ refresh never replays a page that was already written.+ """resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneafter: str | None = resume.after if resume else Noneformatted_cutoff = _format_incremental_value(cutoff) if cutoff is not None else Nonewhile 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")+ items, next_after = _fetch_cursor_page(session, base_url, headers, config, logger, after, formatted_cutoff)stop = _should_stop_desc(items, incremental_field, cutoff)+ if next_after and not stop:+ resumable_source_manager.save_state(TriggerDevResumeConfig(after=next_after))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@@ -209,6 +229,82 @@ def _iter_cursor_pages(resumable_source_manager.clear_state()+def _iter_run_events(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ config: TriggerDevEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TriggerDevResumeConfig],+ cutoff: datetime | None,+) -> Iterator[list[dict[str, Any]]]:+ """Fetch the span events of each run, walking the runs endpoint as the parent.++ The resume state is the runs page cursor plus the last run whose events were yielded, staged before+ that yield. A resumed attempt re-reads the page and skips the runs up to that one, so a full refresh+ never appends the events of a run twice.+ """+ runs_config = TRIGGER_DEV_ENDPOINTS["runs"]+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ after: str | None = resume.after if resume else None+ skip_through: str | None = resume.last_run_id if resume else None+ skip_created_at = resume.last_run_created_at if resume else None+ formatted_cutoff = _format_incremental_value(cutoff) if cutoff is not None else None++ while True:+ runs, next_after = _fetch_cursor_page(session, base_url, headers, runs_config, logger, after, formatted_cutoff)+ stop = _should_stop_desc(runs, runs_config.default_incremental_field, cutoff)+ marker_on_page = skip_through is not None and skip_through in {run.get("id") for run in runs}+ if not runs:+ resumable_source_manager.safe_point()++ for run in runs:+ run_id = run.get("id")+ if not run_id:+ continue+ if skip_through is not None:+ if marker_on_page:+ if run_id == skip_through:+ skip_through = None+ continue+ # The checkpointed run is gone, and the page is newest-first, so every run strictly newer+ # than it was already done.+ created_at = run.get("createdAt")+ if (+ skip_created_at is not None+ and created_at+ and not _is_older_than_cutoff(created_at, dateutil_parser.parse(skip_created_at))+ ):+ continue+ skip_through = None+ if cutoff is not None and _is_older_than_cutoff(run.get("createdAt"), cutoff):+ # Runs from before the cutoff were synced already; the page only crosses it to end the walk.+ continue+ url = _build_url(base_url, config.path.format(run_id=run_id), {})+ try:+ events = _fetch_page(session, url, headers, logger).get("events", []) or []+ except requests.HTTPError as e:+ # A run deleted between the runs page and this request has no events left to sync.+ if e.response is None or e.response.status_code != 404:+ raise+ events = []++ # Stage the run even when it has no events, so a resume does not repeat its request.+ resumable_source_manager.save_state(+ TriggerDevResumeConfig(after=after, last_run_id=run_id, last_run_created_at=run.get("createdAt"))+ )+ if not events:+ resumable_source_manager.safe_point()+ continue+ yield [{**event, "_runs_id": run_id, "_runs_createdAt": run.get("createdAt")} for event in events]++ if stop or not next_after:+ break+ after = next_after++ resumable_source_manager.clear_state()++def _iter_classic_pages(session: requests.Session,base_url: str,@@ -257,9 +353,10 @@ def get_rows(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)+ # Capture off when rows carry a field that must not leave the source: samples are stored before excluded_fields is applied.+ session = make_tracked_session(allow_redirects=False, capture=not config.excluded_fields)- if config.pagination == "cursor":+ if config.pagination in ("cursor", "run_fanout"):cutoff: datetime | None = Noneif should_use_incremental_field and db_incremental_field_last_value is not None:value = db_incremental_field_last_value@@ -272,6 +369,9 @@ def get_rows(value = Noneif isinstance(value, datetime):cutoff = _as_utc(value) - (config.incremental_lookback or timedelta(0))+ if config.pagination == "run_fanout":+ yield from _iter_run_events(session, base_url, headers, config, logger, resumable_source_manager, cutoff)+ returnyield from _iter_cursor_pages(session,base_url,@@ -312,8 +412,8 @@ def trigger_dev_source(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.+ # Runs, deployments, waitpoint tokens and run events arrive newest-first; the pipeline must+ # know so it defers the incremental watermark correctly. Full-refresh endpoints keep asc.sort_mode=endpoint_config.sort_mode,partition_count=1,partition_size=1,