: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 Kestra source (#116914)
Tom Owers2dc08798219a
diff --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 1139299d9adb..5da8105fe2b8 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@@ -6798,10 +6798,10 @@ Today (3): `executions`, `flows`, `triggers`Diffed against: <https://kestra.io/kestra.yml>-- [ ] `Execution task runs (GET /api/v1/{tenant}/executions/{executionId})` — measure task failures, retries, and durations absent from the lightweight execution search results (high)-- [ ] `Flow revisions (GET /api/v1/{tenant}/flows/{namespace}/{id}/revisions)` — resolve flowRevision in executions and compare outcomes across workflow versions (high)-- [ ] `Execution metrics (GET /api/v1/{tenant}/metrics/{executionId})` — analyze task counters and measured values, such as processed rows and bytes (high)-- [ ] `Logs (GET /api/v1/{tenant}/logs/search)` — investigate recurring failures and warnings across executions and tasks (medium)+- [x] `Execution task runs (GET /api/v1/{tenant}/executions/{executionId})` — measure task failures, retries, and durations absent from the lightweight execution search results (high)+- [x] `Flow revisions (GET /api/v1/{tenant}/flows/{namespace}/{id}/revisions)` — resolve flowRevision in executions and compare outcomes across workflow versions (high)+- [x] `Execution metrics (GET /api/v1/{tenant}/metrics/{executionId})` — analyze task counters and measured values, such as processed rows and bytes (high)+- [x] `Logs (GET /api/v1/{tenant}/logs/search)` — investigate recurring failures and warnings across executions and tasks (medium)- [ ] `Task outputs (GET /api/v1/{tenant}/outputs/tasks/{executionId}; GET /api/v1/{tenant}/outputs/tasks/{executionId}/{taskRunId})` — connect workflow results to execution performance and downstream processing (medium)- [ ] `Instance usage (GET /api/v1/{tenant}/usages/all)` — track aggregate execution and flow usage for capacity planning (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/canonical_descriptions.pyindex bd07d63d7def..ff5c9c192c19 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/canonical_descriptions.py@@ -40,4 +40,71 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"state": "Runtime state, evaluation dates, and execution reference for the trigger.",},},+ "task_runs": {+ "description": "Task runs of each execution, with their attempts, state, and timing details.",+ "docs_url": "https://kestra.io/docs/api-reference/open-source",+ "columns": {+ "id": "Unique task run identifier.",+ "executionId": "Identifier of the execution that contains the task run.",+ "namespace": "Namespace that contains the flow.",+ "flowId": "Identifier of the executed flow.",+ "taskId": "Identifier of the task in the flow definition.",+ "parentTaskRunId": "Identifier of the parent task run, for tasks inside a flowable task.",+ "value": "Iteration value, for task runs created by a loop or a parallel task.",+ "attempts": "Attempts of the task run, with the state of each retry.",+ "state": "Task run state, history, start time, end time, and duration.",+ "iteration": "Iteration number of the task run.",+ "execution_start_date": "Start time of the parent execution, used for incremental sync.",+ },+ },+ "execution_metrics": {+ "description": "Counters and timers that tasks emit during each execution.",+ "docs_url": "https://kestra.io/docs/api-reference/open-source",+ "columns": {+ "entry_id": "Hash of the metric entry. Kestra does not give metric entries an identifier.",+ "namespace": "Namespace that contains the flow.",+ "flowId": "Identifier of the executed flow.",+ "taskId": "Identifier of the task that emitted the metric.",+ "executionId": "Identifier of the execution that emitted the metric.",+ "taskRunId": "Identifier of the task run that emitted the metric.",+ "type": "Metric type, such as counter or timer.",+ "name": "Metric name.",+ "value": "Metric value.",+ "timestamp": "Time when the task emitted the metric.",+ "tags": "Tags attached to the metric.",+ "execution_start_date": "Start time of the parent execution, used for incremental sync.",+ },+ },+ "flow_revisions": {+ "description": "Every saved revision of each flow, with its definition and source.",+ "docs_url": "https://kestra.io/docs/api-reference/open-source",+ "columns": {+ "id": "Flow identifier within its namespace.",+ "namespace": "Namespace that contains the flow.",+ "revision": "Revision number of the flow definition.",+ "source": "YAML source of the flow revision.",+ "disabled": "Whether the revision prevents new executions and pauses its triggers.",+ "deleted": "Whether the revision marks the flow as deleted.",+ "tasks": "Tasks defined by the revision.",+ "triggers": "Trigger definitions of the revision.",+ },+ },+ "logs": {+ "description": "Log lines that executions, tasks, and triggers write.",+ "docs_url": "https://kestra.io/docs/api-reference/open-source",+ "columns": {+ "entry_id": "Hash of the log entry. Kestra does not give log entries an identifier.",+ "namespace": "Namespace that contains the flow.",+ "flowId": "Identifier of the flow that wrote the log.",+ "taskId": "Identifier of the task that wrote the log.",+ "executionId": "Identifier of the execution that wrote the log.",+ "taskRunId": "Identifier of the task run that wrote the log.",+ "attemptNumber": "Attempt number of the task run that wrote the log.",+ "triggerId": "Identifier of the trigger that wrote the log.",+ "timestamp": "Time of the log line, used for incremental sync.",+ "level": "Log level, such as ERROR, WARN, INFO, DEBUG, or TRACE.",+ "thread": "Thread that wrote the log line.",+ "message": "Log message.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/kestra.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/kestra.pyindex 2da930c92f75..11c2d5112f87 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/kestra.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/kestra.py@@ -1,9 +1,11 @@import re+import json+import hashlibfrom datetime import UTC, datetimefrom typing import Anyfrom urllib.parse import urlsplit-from requests import Response+from requests import Request, Responsefrom requests.exceptions import HTTPErrorfrom posthog.dataclasses import frozen@@ -11,14 +13,21 @@ from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,+ rest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import create_authfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,PageNumberPaginator,SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ ResponseAction,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse@@ -26,32 +35,88 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.kestra.settings import (AUTH_ERROR,ENDPOINTS,+ FANOUT_PARENTS,+ INCREMENTAL_FIELDS,+ LARGE_PAGE_SIZE,PAGE_SIZE,PERMISSION_ERROR,PRIMARY_KEYS,)+INVALID_PAGE = "Kestra returned an invalid page. Expected results and a total count."+@frozenclass KestraResumeState:page: intstart_date: str | Noneend_date: str+ cursor: str | None = Noneclass KestraPaginator(PageNumberPaginator):- def __init__(self) -> None:+ def __init__(self, page_size: int = PAGE_SIZE) -> None:super().__init__(base_page=1, stop_after_empty_page=False)+ self.page_size = page_sizedef update_state(self, response: Response, data: list[Any] | None = None) -> None:body = response.json()if not isinstance(body.get("results"), list) or not isinstance(body.get("total"), int):- raise ValueError("Kestra returned an invalid page. Expected results and a total count.")+ raise ValueError(INVALID_PAGE)# Trigger pages can be empty when their flows no longer exist, even before the final page.- self.maximum_page = max(1, (body["total"] + PAGE_SIZE - 1) // PAGE_SIZE)+ self.maximum_page = max(1, (body["total"] + self.page_size - 1) // self.page_size)super().update_state(response, data)+class KestraLogPaginator(BasePaginator):+ """Kestra log stores answer with offset pages and a total, or with a forward-only cursor."""++ def __init__(self) -> None:+ super().__init__()+ self.page = 1+ self.cursor: str | None = None++ def init_request(self, request: Request) -> None:+ self.update_request(request)++ def update_state(self, response: Response, data: list[Any] | None = None) -> None:+ body = response.json()+ if not isinstance(body.get("results"), list):+ raise ValueError(INVALID_PAGE)+ next_cursor = body.get("nextCursor")+ if body.get("type") == "CURSOR" or next_cursor:+ if next_cursor and next_cursor == self.cursor:+ raise ValueError("Kestra returned the same log cursor twice.")+ self.cursor = next_cursor or None+ self._has_next_page = self.cursor is not None+ return+ total = body.get("total")+ if not isinstance(total, int):+ raise ValueError(INVALID_PAGE)+ self._has_next_page = self.page * LARGE_PAGE_SIZE < total+ self.page += 1++ def update_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ if self.cursor is None:+ request.params["page"] = self.page+ else:+ request.params.pop("page", None)+ request.params["cursor"] = self.cursor++ def get_resume_state(self) -> dict[str, Any] | None:+ if not self._has_next_page:+ return None+ return {"cursor": self.cursor} if self.cursor is not None else {"page": self.page}++ def set_resume_state(self, state: dict[str, Any]) -> None:+ if state.get("cursor"):+ self.cursor = state["cursor"]+ elif state.get("page"):+ self.page = int(state["page"])++def client_config(config: KestraSourceConfig, team_id: int) -> ClientConfig:from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ( # noqa: PLC0415 -- avoids loading Django models during config discoveryValidateDatabaseHostMixin,@@ -104,7 +169,9 @@ def validate_credentials(config: KestraSourceConfig, team_id: int, schema_name:settings = client_config(config, team_id)except ValueError as error:return False, str(error)- endpoint = schema_for_resource(ENDPOINTS, schema_name or "flows")+ probe_name = schema_name or "flows"+ schema_for_resource(ENDPOINTS, probe_name)+ endpoint = ENDPOINTS[FANOUT_PARENTS.get(probe_name, probe_name)]client = RESTClient(base_url=settings["base_url"],auth=create_auth(settings["auth"]),@@ -133,8 +200,12 @@ def validate_credentials(config: KestraSourceConfig, team_id: int, schema_name:return True, None+def parse_timestamp(value: str) -> datetime:+ return datetime.fromisoformat(value.replace("Z", "+00:00"))++def normalize_execution(row: dict[str, Any]) -> dict[str, Any]:- return {**row, "start_date": datetime.fromisoformat(row["state"]["startDate"].replace("Z", "+00:00"))}+ return {**row, "start_date": parse_timestamp(row["state"]["startDate"])}def normalize_trigger(row: dict[str, Any]) -> dict[str, Any]:@@ -142,30 +213,145 @@ def normalize_trigger(row: dict[str, Any]) -> dict[str, Any]:return {**row, "namespace": state["namespace"], "flow_id": state["flowId"], "trigger_id": state["triggerId"]}+def entry_id(row: dict[str, Any]) -> str:+ # Kestra gives log and metric entries no identifier, so the key is a hash of the entry itself.+ return hashlib.sha256(json.dumps(row, sort_keys=True, default=str).encode()).hexdigest()+++def normalize_log(row: dict[str, Any]) -> dict[str, Any]:+ timestamp = row.get("timestamp")+ return {+ **row,+ "entry_id": entry_id(row),+ "timestamp": parse_timestamp(timestamp) if isinstance(timestamp, str) else timestamp,+ }+++def normalize_task_run(row: dict[str, Any]) -> dict[str, Any]:+ row["execution_start_date"] = row.pop("_executions_start_date")+ return row+++def normalize_metric(row: dict[str, Any]) -> dict[str, Any]:+ execution_start_date = row.pop("_executions_start_date")+ return {**row, "entry_id": entry_id(row), "execution_start_date": execution_start_date}+++def time_window_params(schema_name: str, start_date: str | None, end_date: str) -> dict[str, Any]:+ params: dict[str, Any] = {"filters[endDate][LESS_THAN_OR_EQUAL_TO]": end_date}+ if start_date is not None:+ params["filters[startDate][GREATER_THAN_OR_EQUAL_TO]"] = start_date+ if schema_name == "logs":+ params["sort"] = "timestamp:asc"+ else:+ params.update({"sort": "state.startDate:asc", "dateFilter": "START_DATE"})+ return params+++def fanout_resources(schema_name: str, start_date: str | None, end_date: str) -> list[str | EndpointResource]:+ not_found_is_empty: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]+ if schema_name == "flow_revisions":+ return [+ {+ "name": "flows",+ "endpoint": {+ "path": ENDPOINTS["flows"],+ "params": {"size": PAGE_SIZE, "sort": ["namespace:asc", "id:asc"]},+ "data_selector": "results",+ "data_selector_required": True,+ "paginator": KestraPaginator(),+ },+ },+ {+ "name": schema_name,+ "endpoint": {+ "path": ENDPOINTS[schema_name],+ "params": {+ "namespace": {"type": "resolve", "resource": "flows", "field": "namespace"},+ "id": {"type": "resolve", "resource": "flows", "field": "id"},+ },+ "data_selector_required": True,+ "paginator": SinglePagePaginator(),+ "response_actions": not_found_is_empty,+ },+ },+ ]+ resolve_execution = {"type": "resolve", "resource": "executions", "field": "id"}+ child_endpoint: Endpoint+ if schema_name == "task_runs":+ child_endpoint = {+ "path": ENDPOINTS[schema_name],+ "params": {"executionId": resolve_execution},+ "data_selector": "taskRunList",+ "paginator": SinglePagePaginator(),+ "response_actions": not_found_is_empty,+ }+ else:+ child_endpoint = {+ "path": ENDPOINTS[schema_name],+ "params": {"executionId": resolve_execution, "size": LARGE_PAGE_SIZE},+ "data_selector": "results",+ "data_selector_required": True,+ "paginator": KestraPaginator(LARGE_PAGE_SIZE),+ "response_actions": not_found_is_empty,+ }+ return [+ {+ "name": "executions",+ "endpoint": {+ "path": ENDPOINTS["executions"],+ "params": {"size": PAGE_SIZE, **time_window_params("executions", start_date, end_date)},+ "data_selector": "results",+ "data_selector_required": True,+ "paginator": KestraPaginator(),+ },+ "data_map": normalize_execution,+ },+ {"name": schema_name, "include_from_parent": ["start_date"], "endpoint": child_endpoint},+ ]++def kestra_source(config: KestraSourceConfig, inputs: SourceInputs, manager: ResumableSourceManager[KestraResumeState]) -> SourceResponse:- endpoint = schema_for_resource(ENDPOINTS, inputs.schema_name)+ schema_for_resource(ENDPOINTS, inputs.schema_name)client = client_config(config, inputs.team_id)+ incremental = inputs.schema_name in INCREMENTAL_FIELDSstart_date = None- if inputs.schema_name == "executions" and inputs.should_use_incremental_field:+ if incremental and inputs.should_use_incremental_field:watermark = inputs.db_incremental_field_last_valueif watermark is not None:start_date = watermark.isoformat() if isinstance(watermark, datetime) else str(watermark)+ end_date = datetime.now(UTC).isoformat()++ if inputs.schema_name in FANOUT_PARENTS:+ # Fan-out tables do not resume: the framework would checkpoint every finished parent, which+ # grows with the number of executions or flows.+ resources = rest_api_resources(+ {"client": client, "resources": fanout_resources(inputs.schema_name, start_date, end_date)},+ inputs.team_id,+ inputs.job_id,+ None,+ )+ resource = next(r for r in resources if r.name == inputs.schema_name)+ if inputs.schema_name == "task_runs":+ resource.add_map(normalize_task_run)+ elif inputs.schema_name == "execution_metrics":+ resource.add_map(normalize_metric)+ return SourceResponse(+ name=inputs.schema_name,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS[inputs.schema_name],+ sort_mode="asc" if incremental else "desc",+ on_complete=manager.clear_state,+ )+resume = manager.load_state() if manager.can_resume() else Noneif resume is None:- resume = KestraResumeState(page=1, start_date=start_date, end_date=datetime.now(UTC).isoformat())- params: dict[str, Any] = {"size": PAGE_SIZE}- if inputs.schema_name == "executions":- params.update(- {- "sort": "state.startDate:asc",- "dateFilter": "START_DATE",- "filters[endDate][LESS_THAN_OR_EQUAL_TO]": resume.end_date,- }- )- if resume.start_date is not None:- params["filters[startDate][GREATER_THAN_OR_EQUAL_TO]"] = resume.start_date+ resume = KestraResumeState(page=1, start_date=start_date, end_date=end_date)+ params: dict[str, Any] = {"size": LARGE_PAGE_SIZE if inputs.schema_name == "logs" else PAGE_SIZE}+ if incremental:+ params.update(time_window_params(inputs.schema_name, resume.start_date, resume.end_date))elif inputs.schema_name == "flows":params["sort"] = ["namespace:asc", "id:asc"]else:@@ -174,40 +360,51 @@ def kestra_source(def save_checkpoint(state: dict[str, Any] | None) -> None:if state is not None:manager.save_state(- KestraResumeState(page=int(state["page"]), start_date=resume.start_date, end_date=resume.end_date)+ KestraResumeState(+ page=int(state.get("page") or 1),+ start_date=resume.start_date,+ end_date=resume.end_date,+ cursor=state.get("cursor"),+ ))+ paginator: BasePaginator = KestraLogPaginator() if inputs.schema_name == "logs" else KestraPaginator()rest_config: RESTAPIConfig = {"client": client,"resources": [{"name": inputs.schema_name,"endpoint": {- "path": endpoint,+ "path": ENDPOINTS[inputs.schema_name],"params": params,"data_selector": "results","data_selector_required": True,- "paginator": KestraPaginator(),+ "paginator": paginator,},}],}+ initial_state: dict[str, Any] = {"page": resume.page}+ if resume.cursor is not None:+ initial_state["cursor"] = resume.cursorresource = rest_api_resource(rest_config,inputs.team_id,inputs.job_id,None,resume_hook=save_checkpoint,- initial_paginator_state={"page": resume.page},+ initial_paginator_state=initial_state,)if inputs.schema_name == "executions":resource.add_map(normalize_execution)elif inputs.schema_name == "triggers":resource.add_map(normalize_trigger)+ elif inputs.schema_name == "logs":+ resource.add_map(normalize_log)return SourceResponse(name=inputs.schema_name,items=lambda: resource,primary_keys=PRIMARY_KEYS[inputs.schema_name],- sort_mode="asc" if inputs.schema_name == "executions" else "desc",+ sort_mode="asc" if incremental else "desc",on_complete=manager.clear_state,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/settings.pyindex b08e8162f17d..651b2af678f7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/settings.py@@ -4,14 +4,43 @@ ENDPOINTS = {"executions": "executions/search","flows": "flows/search","triggers": "triggers/search",+ "task_runs": "executions/{executionId}",+ "execution_metrics": "metrics/{executionId}",+ "flow_revisions": "flows/{namespace}/{id}/revisions",+ "logs": "logs/search",+}+# Child tables read one parent row at a time, so a credential probe reads the parent list instead.+FANOUT_PARENTS = {+ "task_runs": "executions",+ "execution_metrics": "executions",+ "flow_revisions": "flows",}PRIMARY_KEYS = {"executions": ["id"],"flows": ["namespace", "id"],"triggers": ["namespace", "flow_id", "trigger_id"],+ "task_runs": ["executionId", "id"],+ "execution_metrics": ["entry_id"],+ "flow_revisions": ["namespace", "id", "revision"],+ "logs": ["entry_id"],+}+INCREMENTAL_FIELDS = {+ "executions": [incremental_field("start_date")],+ "task_runs": [incremental_field("execution_start_date")],+ "execution_metrics": [incremental_field("execution_start_date")],+ "logs": [incremental_field("timestamp")],}-INCREMENTAL_FIELDS = {"executions": [incremental_field("start_date")]}PAGE_SIZE = 100+# Kestra's maximum page size. Log and metric pages are small rows read in bulk.+LARGE_PAGE_SIZE = 1000EXECUTION_LOOKBACK_SECONDS = 7 * 24 * 60 * 60+# Workers write logs asynchronously, so a log can arrive after a later log was already synced.+LOG_LOOKBACK_SECONDS = 60 * 60+LOOKBACK_SECONDS = {+ "executions": EXECUTION_LOOKBACK_SECONDS,+ "task_runs": EXECUTION_LOOKBACK_SECONDS,+ "execution_metrics": EXECUTION_LOOKBACK_SECONDS,+ "logs": LOG_LOOKBACK_SECONDS,+}AUTH_ERROR = "Kestra rejected your credentials. Check your API token or Basic authentication details."PERMISSION_ERROR = "Kestra denied access. Grant read permission for this table in the selected tenant."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/source.pyindex 5f45c89aeadb..4ba575d614d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/source.py@@ -29,8 +29,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.kestra.kesfrom products.warehouse_sources.backend.temporal.data_imports.sources.kestra.settings import (AUTH_ERROR,ENDPOINTS,- EXECUTION_LOOKBACK_SECONDS,INCREMENTAL_FIELDS,+ LOOKBACK_SECONDS,PERMISSION_ERROR,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -73,11 +73,15 @@ class KestraSource(ResumableSource[KestraSourceConfig, KestraResumeState]):force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only={"executions"})- for schema in schemas:- if schema.name == "executions":- schema.default_incremental_lookback_seconds = EXECUTION_LOOKBACK_SECONDS- return schemas+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ merge_only=INCREMENTAL_FIELDS.keys(),+ # Logs hold every debug line of every task, so a user turns them on deliberately.+ should_sync_default={"logs": False},+ default_incremental_lookback_seconds=LOOKBACK_SECONDS,+ )def validate_credentials(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/tests/test_kestra.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/tests/test_kestra.pyindex 7db2460b031f..1f9a711a118b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/tests/test_kestra.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/tests/test_kestra.py@@ -12,12 +12,18 @@ from requests import PreparedRequest, Responsefrom requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+ route,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kestra import (KestraAuthMethodConfig,KestraSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.kestra.kestra import (+ KestraResumeState,kestra_source,validate_credentials,)@@ -182,14 +188,19 @@ def test_catalog_rows_keep_unique_keys(@pytest.mark.parametrize(- "status,schema,valid,message",+ "status,schema,valid,message,probed",[- (200, None, True, None),- (200, "executions", True, None),- (401, None, False, "Kestra rejected"),- (401, "executions", False, "Kestra rejected"),- (403, None, True, None),- (403, "executions", False, "Grant read permission"),+ (200, None, True, None, "flows"),+ (200, "executions", True, None, "executions"),+ (200, "logs", True, None, "logs"),+ (200, "task_runs", True, None, "executions"),+ (200, "execution_metrics", True, None, "executions"),+ (200, "flow_revisions", True, None, "flows"),+ (401, None, False, "Kestra rejected", "flows"),+ (401, "executions", False, "Kestra rejected", "executions"),+ (403, None, True, None, "flows"),+ (403, "executions", False, "Grant read permission", "executions"),+ (403, "flow_revisions", False, "Grant read permission", "flows"),],)def test_credential_probe(@@ -198,6 +209,7 @@ def test_credential_probe(schema: str | None,valid: bool,message: str | None,+ probed: str,) -> None:with patch("requests.sessions.Session.send", return_value=response({"results": [], "total": 0}, status)) as send:success, error = validate_credentials(config, 1, schema)@@ -207,7 +219,7 @@ def test_credential_probe(request = send.call_args.args[0]assert request.headers["Authorization"] == "Bearer test-token"assert parse_qs(urlsplit(request.url or "").query) == {"page": ["1"], "size": ["1"]}- assert urlsplit(request.url or "").path == f"/api/v1/main/{schema or 'flows'}/search"+ assert urlsplit(request.url or "").path == f"/api/v1/main/{probed}/search"@pytest.mark.parametrize("status", [400, 404])@@ -332,3 +344,178 @@ def test_unknown_table_fails_before_request(with pytest.raises(UnknownResourceError):validate_credentials(config, 1, "unknown")send.assert_not_called()+++def page(results: list[dict[str, Any]], total: int) -> ScriptedResponse:+ return ScriptedResponse(json={"results": results, "total": total})++[email protected]("watermark", [datetime(2026, 1, 1, tzinfo=UTC), None])+def test_task_runs_fan_out_over_windowed_executions(config: KestraSourceConfig, watermark: datetime | None) -> None:+ executions = [+ {"id": "run-1", "state": {"startDate": "2026-01-02T00:00:00Z"}},+ {"id": "gone", "state": {"startDate": "2026-01-03T00:00:00Z"}},+ {"id": "run-2", "state": {"startDate": "2026-01-04T00:00:00Z"}},+ ]+ script = route(+ {+ "/api/v1/main/executions/search": [page(executions, 3)],+ "/api/v1/main/executions/run-1": [+ ScriptedResponse(+ json={"id": "run-1", "taskRunList": [{"id": "tr-1", "executionId": "run-1", "taskId": "a"}]}+ )+ ],+ "/api/v1/main/executions/gone": [ScriptedResponse(status=404, json={"message": "Not found"})],+ "/api/v1/main/executions/run-2": [ScriptedResponse(json={"id": "run-2", "taskRunList": None})],+ }+ )+ result = SourceDriver(KestraSource(), config).run(+ "task_runs",+ script,+ incremental_field="execution_start_date",+ db_incremental_field_last_value=watermark,+ )+ assert result.raised is None+ assert result.rows == [+ {+ "id": "tr-1",+ "executionId": "run-1",+ "taskId": "a",+ "execution_start_date": datetime(2026, 1, 2, tzinfo=UTC),+ }+ ]+ search = result.requests[0]+ assert search.param("sort") == "state.startDate:asc"+ assert search.param("dateFilter") == "START_DATE"+ assert search.param("filters[startDate][GREATER_THAN_OR_EQUAL_TO]") == (watermark and watermark.isoformat())+ assert search.param("filters[endDate][LESS_THAN_OR_EQUAL_TO]") is not None+ assert all(request.param("size") is None for request in result.requests[1:])+ assert result.response is not None and result.response.sort_mode == "asc"+++def test_execution_metrics_walk_pages_and_key_each_entry(config: KestraSourceConfig) -> None:+ metric = {"namespace": "ns", "flowId": "f", "executionId": "run-1", "type": "counter", "name": "rows", "value": 5.0}+ script = route(+ {+ "/api/v1/main/executions/search": [+ page([{"id": "run-1", "state": {"startDate": "2026-01-02T00:00:00Z"}}], 1)+ ],+ "/api/v1/main/metrics/run-1": [+ page([{**metric, "timestamp": "2026-01-02T00:00:01Z"}], 1001),+ page([{**metric, "timestamp": "2026-01-02T00:00:02Z"}, {**metric, "tags": {"k": "v"}}], 1001),+ ],+ }+ )+ result = SourceDriver(KestraSource(), config).run(+ "execution_metrics", script, incremental_field="execution_start_date"+ )+ assert result.raised is None+ metric_requests = [request for request in result.requests if "/metrics/" in request.path]+ assert [(request.param("page"), request.param("size")) for request in metric_requests] == [+ ("1", "1000"),+ ("2", "1000"),+ ]+ assert len({row["entry_id"] for row in result.rows}) == 3+ assert {row["execution_start_date"] for row in result.rows} == {datetime(2026, 1, 2, tzinfo=UTC)}+ assert not any(key.startswith("_executions") for row in result.rows for key in row)+++def test_flow_revisions_bind_namespace_and_id(config: KestraSourceConfig) -> None:+ flows = [{"namespace": "company.team", "id": "etl"}, {"namespace": "company.team", "id": "deleted"}]+ script = route(+ {+ "/api/v1/main/flows/search": [page(flows, 2)],+ "/api/v1/main/flows/company.team/etl/revisions": [+ ScriptedResponse(+ json=[+ {"namespace": "company.team", "id": "etl", "revision": 1},+ {"namespace": "company.team", "id": "etl", "revision": 2},+ ]+ )+ ],+ "/api/v1/main/flows/company.team/deleted/revisions": [ScriptedResponse(status=404, json={})],+ }+ )+ result = SourceDriver(KestraSource(), config).run("flow_revisions", script)+ assert result.raised is None+ assert [row["revision"] for row in result.rows] == [1, 2]+ assert result.requests[0].query["sort"] == ("namespace:asc", "id:asc")+++ "answers,expected_pages,expected_cursors",+ [+ (+ [+ {"type": "OFFSET", "total": 1001, "results": [{"message": "first"}]},+ {"type": "OFFSET", "total": 1001, "results": [{"message": "second"}]},+ ],+ ["1", "2"],+ [None, None],+ ),+ (+ [+ {"type": "CURSOR", "nextCursor": "c2", "results": [{"message": "first"}]},+ {"type": "CURSOR", "results": [{"message": "second"}]},+ ],+ ["1", None],+ [None, "c2"],+ ),+ ],+)+def test_logs_walk_offset_and_cursor_pages(+ config: KestraSourceConfig,+ answers: list[dict[str, Any]],+ expected_pages: list[str | None],+ expected_cursors: list[str | None],+) -> None:+ for answer in answers:+ for row in answer["results"]:+ row.update({"namespace": "ns", "flowId": "f", "timestamp": "2026-01-02T03:04:05.123456789Z"})+ result = SourceDriver(KestraSource(), config).run(+ "logs",+ [ScriptedResponse(json=answer) for answer in answers],+ incremental_field="timestamp",+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert result.raised is None+ assert result.params("page") == expected_pages+ assert result.params("cursor") == expected_cursors+ assert result.params("sort") == ["timestamp:asc", "timestamp:asc"]+ assert result.params("filters[startDate][GREATER_THAN_OR_EQUAL_TO]") == ["2026-01-01T00:00:00+00:00"] * 2+ assert [row["message"] for row in result.rows] == ["first", "second"]+ assert result.rows[0]["timestamp"] == datetime(2026, 1, 2, 3, 4, 5, 123456, tzinfo=UTC)+ assert len({row["entry_id"] for row in result.rows}) == 2+ assert len(result.committed_states) == 1+ assert result.completed_state is None+++ "resume,expected_page,expected_cursor",+ [+ (KestraResumeState(page=3, start_date=None, end_date="2026-01-05T00:00:00+00:00"), "3", None),+ (KestraResumeState(page=1, start_date=None, end_date="2026-01-05T00:00:00+00:00", cursor="c9"), None, "c9"),+ ],+)+def test_logs_resume_from_saved_page_or_cursor(+ config: KestraSourceConfig, resume: KestraResumeState, expected_page: str | None, expected_cursor: str | None+) -> None:+ result = SourceDriver(KestraSource(), config).run(+ "logs",+ [ScriptedResponse(json={"type": "OFFSET", "total": 0, "results": []})],+ incremental_field="timestamp",+ resume_state=resume,+ )+ assert result.raised is None+ assert result.params("page") == [expected_page]+ assert result.params("cursor") == [expected_cursor]+ assert result.params("filters[endDate][LESS_THAN_OR_EQUAL_TO]") == ["2026-01-05T00:00:00+00:00"]+++def test_logs_stop_on_a_repeated_cursor(config: KestraSourceConfig) -> None:+ answer = {"type": "CURSOR", "nextCursor": "same", "results": []}+ result = SourceDriver(KestraSource(), config).run(+ "logs", [ScriptedResponse(json=answer), ScriptedResponse(json=answer)], incremental_field="timestamp"+ )+ assert isinstance(result.raised, ValueError)+ assert "same log cursor" in str(result.raised)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/tests/test_kestra_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/tests/test_kestra_source.pydeleted file mode 100644index 1f1bc568612a..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kestra/tests/test_kestra_source.py+++ /dev/null@@ -1,20 +0,0 @@-import pytest--from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import build_default_sync_settings-from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kestra import (- KestraAuthMethodConfig,- KestraSourceConfig,-)-from products.warehouse_sources.backend.temporal.data_imports.sources.kestra.source import KestraSource--[email protected]("names", [None, ["executions"], ["flows"]])-def test_lookback_applies_only_to_execution_syncs(names: list[str] | None) -> None:- config = KestraSourceConfig(host="", tenant="", auth_method=KestraAuthMethodConfig())- schemas = KestraSource().get_schemas(config, 1, names=names)- settings = {schema.name: build_default_sync_settings(schema) for schema in schemas}- if names != ["flows"]:- assert settings["executions"]["incremental_field_lookback_seconds"] == 604800- for name, sync_config in settings.items():- if name != "executions":- assert "incremental_field_lookback_seconds" not in sync_config