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.

fix(data-warehouse): make cancel sync work for v3 pipeline (#68554)

estefania6c9ec282b4a7
diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.py
index 1de0523c125e..ae7cfc6672d2 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py
@@ -6,7 +6,8 @@ from django.db import transaction
import structlog
import temporalio
-from drf_spectacular.utils import extend_schema, extend_schema_field
+from asgiref.sync import async_to_sync
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import filters, serializers, status, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
@@ -44,6 +45,7 @@ from products.data_warehouse.backend.facade.api import (
sync_external_data_job_workflow,
trigger_external_data_workflow,
unpause_external_data_schedule,
+ update_external_job_status,
)
from products.warehouse_sources.backend.facade.models import (
ExternalDataJob,
@@ -53,6 +55,7 @@ from products.warehouse_sources.backend.facade.models import (
sync_frequency_to_sync_frequency_interval,
update_sync_type_config_keys,
)
+from products.warehouse_sources.backend.facade.pipelines import finish_row_tracking
from products.warehouse_sources.backend.facade.source_management import (
RowFilterValidationError,
SourceRegistry,
@@ -1345,6 +1348,22 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return Response(status=status.HTTP_200_OK)
+ @extend_schema(
+ request=None,
+ responses={
+ 200: OpenApiResponse(
+ description="The running sync was cancelled. v3 pipeline jobs are marked Failed immediately; "
+ "for older pipeline versions the cancelled workflow records the final status.",
+ ),
+ 400: OpenApiResponse(
+ response={
+ "type": "object",
+ "properties": {"detail": {"type": "string"}},
+ },
+ description="No running sync to cancel, or the sync already finished.",
+ ),
+ },
+ )
@action(methods=["POST"], detail=True)
def cancel(self, request: Request, *args: Any, **kwargs: Any):
instance: ExternalDataSchema = self.get_object()
@@ -1361,15 +1380,58 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
data={"detail": "No running sync to cancel."},
)
- try:
- cancel_external_data_workflow(latest_running_job.workflow_id)
- except temporalio.service.RPCError as e:
- logger.exception(f"Could not cancel external data workflow for schema {instance.id}", exc_info=e)
+ if latest_running_job.pipeline_version != ExternalDataJob.PipelineVersion.V3:
+ # v1/v2: the workflow itself owns the job's terminal status, so keep the legacy
+ # behavior where the cancel RPC is the whole operation and a missing workflow
+ # is an error.
+ try:
+ cancel_external_data_workflow(latest_running_job.workflow_id)
+ except temporalio.service.RPCError as e:
+ logger.exception(f"Could not cancel external data workflow for schema {instance.id}", exc_info=e)
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"detail": "Could not find workflow to cancel. The sync may have already finished."},
+ )
+ return Response(status=status.HTTP_200_OK)
+
+ # v3: durable marker FIRST. Failed is terminal/absorbing, so the loader's later
+ # Completed write and the workflow finally-block write become no-ops.
+ model = update_external_job_status(
+ job_id=str(latest_running_job.id),
+ team_id=instance.team_id,
+ status=ExternalDataJob.Status.FAILED,
+ logger=logger,
+ latest_error="Sync cancelled by user",
+ )
+ if model.status != ExternalDataJob.Status.FAILED:
+ # The job reached a different terminal state concurrently (e.g. Completed).
return Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"detail": "Could not find workflow to cancel. The sync may have already finished."},
+ data={"detail": "The sync already finished."},
)
+ try:
+ cancel_external_data_workflow(latest_running_job.workflow_id)
+ except temporalio.service.RPCError as e:
+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:
+ # v3 loading phase: the extraction workflow already completed while the loader
+ # drains batches. The Failed marker above makes the loader skip and clean up.
+ logger.info("cancel_sync_workflow_already_finished", schema_id=str(instance.id))
+ else:
+ # Transient RPC failure against a possibly-live workflow. The Failed marker is
+ # already durable (terminal statuses absorb the workflow's later writes, and the
+ # v3 loader cleans up off the marker), so the cancel stands - but the workflow
+ # may keep running until it finishes on its own, so surface the failure.
+ logger.exception("cancel_sync_workflow_cancel_rpc_failed", schema_id=str(instance.id))
+
+ try:
+ # Clear the schema's in-flight row counter; nothing will finish it once the job is Failed.
+ async_to_sync(finish_row_tracking)(instance.team_id, str(instance.id))
+ except Exception as e:
+ # Best-effort: the counter is rebuilt from scratch by the next sync.
+ logger.exception("cancel_sync_row_tracking_cleanup_failed", schema_id=str(instance.id))
+ capture_exception(e)
+
return Response(status=status.HTTP_200_OK)
@action(methods=["DELETE"], detail=True)
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_schema.py b/products/data_warehouse/backend/tests/api/test_external_data_schema.py
index 55382659e7bf..e7f0116003a8 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_schema.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_schema.py
@@ -2826,8 +2826,9 @@ class TestUpdateExternalDataSchema:
class TestCancelExternalDataSchema(APIBaseTest):
- @mock.patch("products.data_warehouse.backend.presentation.views.external_data_schema.cancel_external_data_workflow")
- def test_cancel_running_sync(self, mock_cancel):
+ def _create_schema_with_running_job(self, pipeline_version=None):
+ from products.warehouse_sources.backend.facade.models import ExternalDataJob
+
source = ExternalDataSource.objects.create(
team=self.team, source_type=ExternalDataSourceType.STRIPE, job_inputs={"stripe_secret_key": "123"}
)
@@ -2839,16 +2840,87 @@ class TestCancelExternalDataSchema(APIBaseTest):
status=ExternalDataSchema.Status.RUNNING,
sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
)
- from products.warehouse_sources.backend.facade.models import ExternalDataJob
-
job = ExternalDataJob.objects.create(
team=self.team,
pipeline=source,
schema=schema,
status=ExternalDataJob.Status.RUNNING,
workflow_id="test-workflow-id",
+ pipeline_version=pipeline_version,
+ )
+ return schema, job
+
+ @mock.patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.finish_row_tracking",
+ new_callable=mock.AsyncMock,
+ )
+ @mock.patch("products.data_warehouse.backend.presentation.views.external_data_schema.cancel_external_data_workflow")
+ def test_cancel_running_v3_sync_marks_job_failed(self, mock_cancel, mock_finish_row_tracking):
+ from products.warehouse_sources.backend.facade.models import ExternalDataJob
+
+ schema, job = self._create_schema_with_running_job(pipeline_version=ExternalDataJob.PipelineVersion.V3)
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/cancel/",
+ )
+
+ assert response.status_code == 200
+ mock_cancel.assert_called_once_with(job.workflow_id)
+
+ job.refresh_from_db()
+ schema.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.FAILED
+ assert job.latest_error == "Sync cancelled by user"
+ assert schema.status == ExternalDataSchema.Status.FAILED
+ # Nothing will finish the in-flight row counter once the job is Failed, so cancel must.
+ mock_finish_row_tracking.assert_awaited_once_with(self.team.pk, str(schema.id))
+
+ @parameterized.expand(
+ [
+ # v3 loading phase: the extraction workflow completed but the job stays Running while
+ # the loader drains batches. Cancel must mark the job Failed (the loader acts on that
+ # marker) instead of returning a 400.
+ ("workflow_already_finished", "NOT_FOUND"),
+ # Transient RPC failure: the Failed marker is durable and absorbing, so the cancel
+ # stands and a 500 would strand the user (the job is no longer Running, so a retry
+ # can't reach the workflow again).
+ ("transient_rpc_failure", "UNAVAILABLE"),
+ ]
+ )
+ @mock.patch(
+ "products.data_warehouse.backend.presentation.views.external_data_schema.finish_row_tracking",
+ new_callable=mock.AsyncMock,
+ )
+ @mock.patch("products.data_warehouse.backend.presentation.views.external_data_schema.cancel_external_data_workflow")
+ def test_cancel_v3_succeeds_when_cancel_rpc_fails(self, _case, rpc_status_name, mock_cancel, _mock_finish):
+ from temporalio.service import RPCError, RPCStatusCode
+
+ from products.warehouse_sources.backend.facade.models import ExternalDataJob
+
+ schema, job = self._create_schema_with_running_job(pipeline_version=ExternalDataJob.PipelineVersion.V3)
+ mock_cancel.side_effect = RPCError("cancel failed", RPCStatusCode[rpc_status_name], b"")
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/cancel/",
)
+ assert response.status_code == 200
+
+ job.refresh_from_db()
+ schema.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.FAILED
+ assert job.latest_error == "Sync cancelled by user"
+ assert schema.status == ExternalDataSchema.Status.FAILED
+
+ @parameterized.expand([("v1", "v1-dlt-sync"), ("legacy_null_version", None)])
+ @mock.patch("products.data_warehouse.backend.presentation.views.external_data_schema.cancel_external_data_workflow")
+ def test_cancel_legacy_pipeline_leaves_status_to_the_workflow(self, _case, pipeline_version, mock_cancel):
+ # Pre-v3 pipelines: the cancelled workflow records the job's terminal status itself,
+ # so the endpoint must not write a Failed marker.
+ from products.warehouse_sources.backend.facade.models import ExternalDataJob
+
+ schema, job = self._create_schema_with_running_job(pipeline_version=pipeline_version)
+
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/cancel/",
)
@@ -2856,6 +2928,28 @@ class TestCancelExternalDataSchema(APIBaseTest):
assert response.status_code == 200
mock_cancel.assert_called_once_with(job.workflow_id)
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.RUNNING
+ assert job.latest_error is None
+
+ @mock.patch("products.data_warehouse.backend.presentation.views.external_data_schema.cancel_external_data_workflow")
+ def test_cancel_legacy_pipeline_returns_400_when_workflow_missing(self, mock_cancel):
+ from temporalio.service import RPCError, RPCStatusCode
+
+ from products.warehouse_sources.backend.facade.models import ExternalDataJob
+
+ schema, job = self._create_schema_with_running_job(pipeline_version=ExternalDataJob.PipelineVersion.V1)
+ mock_cancel.side_effect = RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b"")
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/cancel/",
+ )
+
+ assert response.status_code == 400
+
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.RUNNING
+
@mock.patch("products.data_warehouse.backend.presentation.views.external_data_schema.cancel_external_data_workflow")
def test_cancel_when_no_running_job(self, mock_cancel):
source = ExternalDataSource.objects.create(
diff --git a/products/warehouse_sources/backend/facade/pipelines.py b/products/warehouse_sources/backend/facade/pipelines.py
index a34b283e1183..69cbc5d8cad4 100644
--- a/products/warehouse_sources/backend/facade/pipelines.py
+++ b/products/warehouse_sources/backend/facade/pipelines.py
@@ -23,6 +23,7 @@ _LAZY = {
"SyncNewSchemasActivityInputs": "workflow_activities.sync_new_schemas",
"DUCKGRES_BATCH_SINK_FLAG": "pipelines.pipeline_v3.duckgres.enablement",
"is_duckgres_sink_team_member": "pipelines.pipeline_v3.duckgres.enablement",
+ "finish_row_tracking": "row_tracking",
"HealthState": "pipelines.pipeline_v3.load.health",
"start_health_server": "pipelines.pipeline_v3.load.health",
"ensure_bucket": "pipelines.pipeline_v3.s3.common",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index f58f0acf6dc4..0b2756ee932f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -277,9 +277,7 @@ def _release_pipeline_lock_for_job(export_signal: ExportSignalMessage) -> None:
def _mark_job_completed(export_signal: ExportSignalMessage) -> None:
- _promote_staged_cursor(export_signal)
-
- update_external_job_status(
+ model = update_external_job_status(
job_id=export_signal.job_id,
team_id=export_signal.team_id,
status=ExternalDataJob.Status.COMPLETED,
@@ -287,14 +285,28 @@ def _mark_job_completed(export_signal: ExportSignalMessage) -> None:
latest_error=None,
)
- async_to_sync(finish_row_tracking)(export_signal.team_id, export_signal.schema_id)
+ if model.status == ExternalDataJob.Status.COMPLETED:
+ # Promote only when the Completed write landed: if the job was cancelled (absorbing
+ # Failed) after the final batch passed should_process_batch, the staged incremental
+ # cursor must not advance past data that was never fully loaded.
+ _promote_staged_cursor(export_signal)
- logger.info(
- "job_marked_completed",
- external_data_job_id=export_signal.job_id,
- team_id=export_signal.team_id,
- external_data_schema_id=export_signal.schema_id,
- )
+ async_to_sync(finish_row_tracking)(export_signal.team_id, export_signal.schema_id)
+
+ logger.info(
+ "job_marked_completed",
+ external_data_job_id=export_signal.job_id,
+ team_id=export_signal.team_id,
+ external_data_schema_id=export_signal.schema_id,
+ )
+ else:
+ logger.info(
+ "job_completion_suppressed_terminal_status",
+ external_data_job_id=export_signal.job_id,
+ team_id=export_signal.team_id,
+ external_data_schema_id=export_signal.schema_id,
+ status=model.status,
+ )
_release_pipeline_lock_for_job(export_signal)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index cf2b5d34238b..50cffefb9023 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -10,12 +10,24 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (
_apply_partitioning,
_get_write_type,
+ _mark_job_completed,
_promote_staged_cursor,
process_message,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.test_mocks import mock_delta_table
[email protected](autouse=True)
+def _no_close_old_connections():
+ # These are pure unit tests, but close_old_connections() touches the Django
+ # connection, which pytest-django blocks for unmarked tests once a django_db
+ # test has run in the same session — an order-dependent failure.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.close_old_connections"
+ ):
+ yield
+
+
class TestGetWriteType:
@parameterized.expand(
[
@@ -260,3 +272,69 @@ class TestProcessMessageOwnershipGate:
mock_post_load.assert_not_called()
mock_mark_completed.assert_not_called()
+
+
+class TestMarkJobCompleted:
+ def _make_signal(self, **overrides: Any) -> MagicMock:
+ signal = MagicMock()
+ signal.schema_id = overrides.get("schema_id", "schema-1")
+ signal.team_id = overrides.get("team_id", 1)
+ signal.run_uuid = overrides.get("run_uuid", "run-abc-a1")
+ signal.job_id = overrides.get("job_id", "job-1")
+ return signal
+
+ @parameterized.expand(
+ [
+ # If the job was cancelled (absorbing Failed) after the final batch passed
+ # should_process_batch, the Completed write is rejected and the staged
+ # incremental cursor must NOT be promoted.
+ ("completed_write_lands", "Completed", True),
+ ("completed_write_absorbed_by_failed", "Failed", False),
+ ]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.release_v3_pipeline_lock"
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.ExternalDataJob.objects"
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.finish_row_tracking",
+ new_callable=AsyncMock,
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.ExternalDataSchema.objects"
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.update_external_job_status"
+ )
+ def test_promotes_cursor_only_when_completed_write_lands(
+ self,
+ _case: str,
+ resulting_status: str,
+ expect_promotion: bool,
+ mock_update: MagicMock,
+ mock_schema_objects: MagicMock,
+ mock_finish_row_tracking: AsyncMock,
+ mock_job_objects: MagicMock,
+ mock_release: MagicMock,
+ ) -> None:
+ model = MagicMock()
+ model.status = resulting_status
+ mock_update.return_value = model
+
+ schema = MagicMock()
+ mock_schema_objects.get.return_value = schema
+ job = MagicMock()
+ job.workflow_run_id = "wf-run-1"
+ mock_job_objects.only.return_value.get.return_value = job
+
+ _mark_job_completed(self._make_signal())
+
+ if expect_promotion:
+ schema.promote_staged_incremental_values.assert_called_once_with("run-abc-a1")
+ else:
+ schema.promote_staged_incremental_values.assert_not_called()
+ mock_finish_row_tracking.assert_not_awaited()
+ # The pipeline lock must be released either way, or the next sync is blocked.
+ mock_release.assert_called_once_with(team_id=1, schema_id="schema-1", token="wf-run-1")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 259cc8c0ba6b..bc2acb265a8b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -7,6 +7,7 @@ polling, retry, and recovery mechanics to the v3 batch consumer engine.
from __future__ import annotations
+import time
import asyncio
from collections.abc import Callable, Coroutine
from datetime import datetime
@@ -20,7 +21,10 @@ from asgiref.sync import sync_to_async
from posthog.exceptions_capture import capture_exception
-from products.warehouse_sources.backend.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES
+from products.warehouse_sources.backend.temporal.data_imports.metrics import (
+ LOCK_TAKEOVER_LATEST_ERROR,
+ TERMINAL_JOB_STATUSES,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
MAX_ATTEMPTS,
POLL_INTERVAL_SECONDS,
@@ -71,6 +75,13 @@ NON_RETRYABLE_ERROR_PATTERNS: tuple[str, ...] = (
"Primary key required for incremental syncs",
)
+# How long an "alive" job-status lookup stays cached before re-checking the app DB.
+# Dead results never expire — a terminal job never comes back to life — and eviction
+# drops alive entries first, so a dead verdict survives until the cache overflows
+# with dead entries alone.
+JOB_STATUS_CACHE_TTL_SECONDS = 30
+JOB_STATUS_CACHE_MAX_ENTRIES = 1000
+
class DeltaBatchConsumerAdapter:
log_prefix: str = ""
@@ -79,6 +90,10 @@ class DeltaBatchConsumerAdapter:
waiting_retry_state: str = SourceBatchStatus.State.WAITING_RETRY.value
per_group_connections: bool = True
+ def __init__(self) -> None:
+ # job_id -> (is_dead, checked_at via time.monotonic())
+ self._job_dead_cache: dict[str, tuple[bool, float]] = {}
+
async def fetch_and_lock(
self,
conn: psycopg.AsyncConnection[Any],
@@ -338,7 +353,56 @@ class DeltaBatchConsumerAdapter:
*,
batch: PendingBatch,
) -> bool:
- return True
+ try:
+ job_dead = await self._is_job_dead(batch)
+ except Exception as e:
+ # Fail open: an app-DB hiccup must never wedge the loader.
+ logger.exception("job_status_check_failed", batch_id=batch.id, job_id=batch.job_id)
+ capture_exception(e)
+ return True
+
+ if not job_dead:
+ return True
+
+ logger.warning(
+ "skipping_batch_for_dead_job",
+ batch_id=batch.id,
+ job_id=batch.job_id,
+ run_uuid=batch.run_uuid,
+ )
+ await self.fail_run(conn, batch=batch, reason="sync cancelled or job failed")
+ return False
+
+ async def _is_job_dead(self, batch: PendingBatch) -> bool:
+ """Whether the batch's ExternalDataJob is in a terminal non-Completed state (e.g. cancelled)."""
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ now = time.monotonic()
+ cached = self._job_dead_cache.get(batch.job_id)
+ if cached is not None:
+ is_dead, checked_at = cached
+ if is_dead or now - checked_at < JOB_STATUS_CACHE_TTL_SECONDS:
+ return is_dead
+
+ row = await sync_to_async(_get_job_status_and_error)(job_id=batch.job_id, team_id=batch.team_id)
+ is_dead = (
+ row is not None
+ and row[0] in TERMINAL_JOB_STATUSES
+ and row[0] != ExternalDataJob.Status.COMPLETED
+ # A takeover-failed job stays loadable: only the exact takeover sentinel
+ # unseals Failed -> Completed in update_external_job_status, and skipping
+ # its batches here would close that deliberate recovery window.
+ and row[1] != LOCK_TAKEOVER_LATEST_ERROR
+ )
+
+ if len(self._job_dead_cache) >= JOB_STATUS_CACHE_MAX_ENTRIES:
+ # Evict alive entries first: dead verdicts are final, and re-deriving one
+ # costs an app-DB read per queued batch of that job.
+ self._job_dead_cache = {k: v for k, v in self._job_dead_cache.items() if v[0]}
+ if len(self._job_dead_cache) >= JOB_STATUS_CACHE_MAX_ENTRIES:
+ self._job_dead_cache.clear()
+ self._job_dead_cache[batch.job_id] = (is_dead, now)
+ return is_dead
def is_retryable_error(self, err: Exception) -> bool:
message = str(err)
@@ -393,6 +457,15 @@ class BatchConsumer(SharedBatchConsumer):
return verify_ownership
+def _get_job_status_and_error(*, job_id: str, team_id: int) -> tuple[str, str | None] | None:
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ # Drop stale app-DB connections so this read reconnects instead of erroring.
+ close_old_connections()
+
+ return ExternalDataJob.objects.filter(id=job_id, team_id=team_id).values_list("status", "latest_error").first()
+
+
def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str) -> None:
from products.data_warehouse.backend.facade.api import update_external_job_status
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
@@ -419,12 +492,8 @@ def mark_job_failed_if_not_terminal(*, job_id: str, team_id: int, error: str) ->
Public seam shared by the reconcile sweep and the manage_warehouse_queue ops
command, so both fail paths agree on the terminal-status check.
"""
- from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-
- close_old_connections()
-
- job = ExternalDataJob.objects.filter(id=job_id, team_id=team_id).only("status").first()
- if job is None or job.status in TERMINAL_JOB_STATUSES:
+ row = _get_job_status_and_error(job_id=job_id, team_id=team_id)
+ if row is None or row[0] in TERMINAL_JOB_STATUSES:
return False
_update_job_status_to_failed(job_id=job_id, team_id=team_id, error=error)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index 9d48b7ea7783..7140d66a36a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, patch
import psycopg
import structlog
+from products.warehouse_sources.backend.temporal.data_imports.metrics import LOCK_TAKEOVER_LATEST_ERROR
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import (
batch_consumer as batch_consumer_module,
)
@@ -737,6 +738,99 @@ class TestFailRun:
mock_status.assert_called_once()
+class TestShouldProcessBatch:
+ @pytest.mark.parametrize("job_status", ["Failed", "BillingLimitReached"], ids=["failed", "billing_limited"])
+ @pytest.mark.asyncio
+ async def test_dead_job_fails_run_and_skips(self, job_status):
+ # Cancel (or any failure) marks the job terminal while batches are still queued:
+ # the loader must not load them, and must clear the run + release the pipeline lock.
+ consumer = _make_consumer()
+ conn = consumer._poll_conn
+ assert conn is not None
+ batch = _make_batch(metadata={"workflow_run_id": "wf-run-1"})
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._get_job_status_and_error",
+ return_value=(job_status, "connection lost"),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ) as mock_queue_fail,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._update_job_status_to_failed",
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.release_v3_pipeline_lock",
+ ) as mock_release,
+ ):
+ result = await consumer._adapter.should_process_batch(conn, batch=batch)
+
+ assert result is False
+ mock_queue_fail.assert_awaited_once()
+ assert mock_queue_fail.call_args.kwargs["run_uuid"] == batch.run_uuid
+ mock_release.assert_called_once_with(team_id=batch.team_id, schema_id=batch.schema_id, token="wf-run-1")
+
+ @pytest.mark.parametrize(
+ "status_row",
+ [
+ ("Running", None),
+ ("Completed", None),
+ None,
+ # A takeover-failed job stays loadable: the sentinel unseals Failed -> Completed
+ # in update_external_job_status, so skipping its batches here would close that
+ # deliberate in-flight recovery window.
+ ("Failed", LOCK_TAKEOVER_LATEST_ERROR),
+ ],
+ ids=["running", "completed", "missing", "takeover_failed"],
+ )
+ @pytest.mark.asyncio
+ async def test_loadable_job_is_processed(self, status_row):
+ consumer = _make_consumer()
+ conn = consumer._poll_conn
+ assert conn is not None
+ batch = _make_batch()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._get_job_status_and_error",
+ return_value=status_row,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ) as mock_queue_fail,
+ ):
+ result = await consumer._adapter.should_process_batch(conn, batch=batch)
+
+ assert result is True
+ mock_queue_fail.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_status_check_db_error_fails_open(self):
+ # An app-DB hiccup must not wedge the loader: process the batch as if the job were alive.
+ consumer = _make_consumer()
+ conn = consumer._poll_conn
+ assert conn is not None
+ batch = _make_batch()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._get_job_status_and_error",
+ side_effect=Exception("db down"),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ) as mock_queue_fail,
+ ):
+ result = await consumer._adapter.should_process_batch(conn, batch=batch)
+
+ assert result is True
+ mock_queue_fail.assert_not_called()
+
+
class TestReconcileFailedRuns:
@pytest.mark.asyncio
async def test_reconcile_reports_queue_freshness_gauge(self):
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 5b9ab9cac6c9..4d960ba2d119 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -7043,6 +7043,10 @@ export type ExternalDataSchemasListParams = {
search?: string
}
+export type ExternalDataSchemasCancelCreate400 = {
+ detail?: string
+}
+
export type ExternalDataSchemasLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp.
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index abbc3054e816..cc46ba2aa9b1 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -176,14 +176,11 @@ export const getExternalDataSchemasCancelCreateUrl = (projectId: string, id: str
export const externalDataSchemasCancelCreate = async (
projectId: string,
id: string,
- externalDataSchemaApi?: NonReadonly<ExternalDataSchemaApi>,
options?: RequestInit
): Promise<void> => {
return apiMutator<void>(getExternalDataSchemasCancelCreateUrl(projectId, id), {
...options,
method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(externalDataSchemaApi),
})
}
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index dde0ecc27aac..81ae8198cc3d 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -315,108 +315,6 @@ export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({
),
})
-export const externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMin = 0
-export const externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMax = 5184000
-
-export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
- should_sync: zod.boolean().optional(),
- sync_type: zod
- .union([
- zod
- .enum(['full_refresh', 'incremental', 'append', 'webhook', 'cdc', 'xmin'])
- .describe(
- '\* `full_refresh` - full_refresh\n\* `incremental` - incremental\n\* `append` - append\n\* `webhook` - webhook\n\* `cdc` - cdc\n\* `xmin` - xmin'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Sync strategy: incremental, full_refresh, append, cdc, or xmin.\n\n\* `full_refresh` - full_refresh\n\* `incremental` - incremental\n\* `append` - append\n\* `webhook` - webhook\n\* `cdc` - cdc\n\* `xmin` - xmin'
- ),
- incremental_field: zod.string().nullish().describe('Column name used to track sync progress.'),
- incremental_field_type: zod
- .union([
- zod
- .enum(['integer', 'numeric', 'datetime', 'date', 'timestamp', 'objectid', 'xid'])
- .describe(
- '\* `integer` - integer\n\* `numeric` - numeric\n\* `datetime` - datetime\n\* `date` - date\n\* `timestamp` - timestamp\n\* `objectid` - objectid\n\* `xid` - xid'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Data type of the incremental field.\n\n\* `integer` - integer\n\* `numeric` - numeric\n\* `datetime` - datetime\n\* `date` - date\n\* `timestamp` - timestamp\n\* `objectid` - objectid\n\* `xid` - xid'
- ),
- incremental_field_lookback_seconds: zod
- .number()
- .min(externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMin)
- .max(externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMax)
- .nullish()
- .describe(
- 'Seconds to subtract from the stored incremental watermark at sync time, so each incremental run re-reads a rolling overlap window and catches late or backdated rows. Applies to timestamp\/date incremental fields only. The stored watermark is unchanged. Maximum 5184000 (60 days).'
- ),
- sync_frequency: zod
- .union([
- zod
- .enum([
- 'never',
- '1min',
- '5min',
- '15min',
- '30min',
- '1hour',
- '6hour',
- '12hour',
- '24hour',
- '7day',
- '30day',
- ])
- .describe(
- '\* `never` - never\n\* `1min` - 1min\n\* `5min` - 5min\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'How often to sync.\n\n\* `never` - never\n\* `1min` - 1min\n\* `5min` - 5min\n\* `15min` - 15min\n\* `30min` - 30min\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day\n\* `30day` - 30day'
- ),
- sync_time_of_day: zod.iso.time({}).nullish().describe('UTC time of day to run the sync (HH:MM:SS).'),
- primary_key_columns: zod.array(zod.string()).nullish().describe('Column names for primary key deduplication.'),
- cdc_table_mode: zod
- .union([
- zod
- .enum(['consolidated', 'cdc_only', 'both'])
- .describe('\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'),
- zod.null(),
- ])
- .optional()
- .describe(
- 'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
- ),
- enabled_columns: zod
- .array(zod.string())
- .nullish()
- .describe(
- 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
- ),
- row_filters: zod
- .array(
- zod.object({
- column: zod.string(),
- operator: zod.string().describe('One of: > >= < <= = != IN \"NOT IN\".'),
- value: zod
- .unknown()
- .describe(
- "Comparison value; must match the column's type. For `IN` \/ `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
- ),
- })
- )
- .nullish()
- .describe(
- "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`\/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`\/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
- ),
-})
-
export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMin = 0
export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMax = 5184000
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 205e2b5062e9..f6a3f30d5720 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -63666,6 +63666,10 @@ export namespace Schemas {
search?: string;
};
+ export type EnvironmentsExternalDataSchemasCancelCreate400 = {
+ detail?: string;
+ };
+
export type EnvironmentsExternalDataSchemasLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp.
@@ -70789,6 +70793,10 @@ export namespace Schemas {
search?: string;
};
+ export type ExternalDataSchemasCancelCreate400 = {
+ detail?: string;
+ };
+
export type ExternalDataSchemasLogsRetrieveParams = {
/**
* Only return entries after this ISO 8601 timestamp.
diff --git a/services/mcp/src/generated/warehouse_sources/api.ts b/services/mcp/src/generated/warehouse_sources/api.ts
index 38130b8d583e..a9150f79fe1e 100644
--- a/services/mcp/src/generated/warehouse_sources/api.ts
+++ b/services/mcp/src/generated/warehouse_sources/api.ts
@@ -151,108 +151,6 @@ export const ExternalDataSchemasCancelCreateParams = /* @__PURE__ */ zod.object(
),
})
-export const externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMin = 0
-export const externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMax = 5184000
-
-export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
- should_sync: zod.boolean().optional(),
- sync_type: zod
- .union([
- zod
- .enum(['full_refresh', 'incremental', 'append', 'webhook', 'cdc', 'xmin'])
- .describe(
- '* `full_refresh` - full_refresh\n* `incremental` - incremental\n* `append` - append\n* `webhook` - webhook\n* `cdc` - cdc\n* `xmin` - xmin'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Sync strategy: incremental, full_refresh, append, cdc, or xmin.\n\n* `full_refresh` - full_refresh\n* `incremental` - incremental\n* `append` - append\n* `webhook` - webhook\n* `cdc` - cdc\n* `xmin` - xmin'
- ),
- incremental_field: zod.string().nullish().describe('Column name used to track sync progress.'),
- incremental_field_type: zod
- .union([
- zod
- .enum(['integer', 'numeric', 'datetime', 'date', 'timestamp', 'objectid', 'xid'])
- .describe(
- '* `integer` - integer\n* `numeric` - numeric\n* `datetime` - datetime\n* `date` - date\n* `timestamp` - timestamp\n* `objectid` - objectid\n* `xid` - xid'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'Data type of the incremental field.\n\n* `integer` - integer\n* `numeric` - numeric\n* `datetime` - datetime\n* `date` - date\n* `timestamp` - timestamp\n* `objectid` - objectid\n* `xid` - xid'
- ),
- incremental_field_lookback_seconds: zod
- .number()
- .min(externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMin)
- .max(externalDataSchemasCancelCreateBodyIncrementalFieldLookbackSecondsMax)
- .nullish()
- .describe(
- 'Seconds to subtract from the stored incremental watermark at sync time, so each incremental run re-reads a rolling overlap window and catches late or backdated rows. Applies to timestamp/date incremental fields only. The stored watermark is unchanged. Maximum 5184000 (60 days).'
- ),
- sync_frequency: zod
- .union([
- zod
- .enum([
- 'never',
- '1min',
- '5min',
- '15min',
- '30min',
- '1hour',
- '6hour',
- '12hour',
- '24hour',
- '7day',
- '30day',
- ])
- .describe(
- '* `never` - never\n* `1min` - 1min\n* `5min` - 5min\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day'
- ),
- zod.null(),
- ])
- .optional()
- .describe(
- 'How often to sync.\n\n* `never` - never\n* `1min` - 1min\n* `5min` - 5min\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day'
- ),
- sync_time_of_day: zod.iso.time({}).nullish().describe('UTC time of day to run the sync (HH:MM:SS).'),
- primary_key_columns: zod.array(zod.string()).nullish().describe('Column names for primary key deduplication.'),
- cdc_table_mode: zod
- .union([
- zod
- .enum(['consolidated', 'cdc_only', 'both'])
- .describe('* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both'),
- zod.null(),
- ])
- .optional()
- .describe(
- 'For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both'
- ),
- enabled_columns: zod
- .array(zod.string())
- .nullish()
- .describe(
- 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
- ),
- row_filters: zod
- .array(
- zod.object({
- column: zod.string(),
- operator: zod.string().describe('One of: > >= < <= = != IN "NOT IN".'),
- value: zod
- .unknown()
- .describe(
- "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
- ),
- })
- )
- .nullish()
- .describe(
- "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
- ),
-})
-
export const ExternalDataSchemasDeleteDataDestroyParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this external data schema.'),
project_id: zod
diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.ts
index bd98f0a474f4..ae3516c2446a 100644
--- a/services/mcp/src/tools/generated/warehouse_sources.ts
+++ b/services/mcp/src/tools/generated/warehouse_sources.ts
@@ -3,7 +3,6 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
- ExternalDataSchemasCancelCreateBody,
ExternalDataSchemasCancelCreateParams,
ExternalDataSchemasDeleteDataDestroyParams,
ExternalDataSchemasIncrementalFieldsCreateBody,
@@ -123,53 +122,16 @@ const dataWarehouseStoredCredentialsList = (): ToolBase<
},
})
-const ExternalDataSchemasCancelSchema = ExternalDataSchemasCancelCreateParams.omit({ project_id: true }).extend(
- ExternalDataSchemasCancelCreateBody.shape
-)
+const ExternalDataSchemasCancelSchema = ExternalDataSchemasCancelCreateParams.omit({ project_id: true })
const externalDataSchemasCancel = (): ToolBase<typeof ExternalDataSchemasCancelSchema, unknown> => ({
name: 'external-data-schemas-cancel',
schema: ExternalDataSchemasCancelSchema,
handler: async (context: Context, params: z.infer<typeof ExternalDataSchemasCancelSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.should_sync !== undefined) {
- body['should_sync'] = params.should_sync
- }
- if (params.sync_type !== undefined) {
- body['sync_type'] = params.sync_type
- }
- if (params.incremental_field !== undefined) {
- body['incremental_field'] = params.incremental_field
- }
- if (params.incremental_field_type !== undefined) {
- body['incremental_field_type'] = params.incremental_field_type
- }
- if (params.incremental_field_lookback_seconds !== undefined) {
- body['incremental_field_lookback_seconds'] = params.incremental_field_lookback_seconds
- }
- if (params.sync_frequency !== undefined) {
- body['sync_frequency'] = params.sync_frequency
- }
- if (params.sync_time_of_day !== undefined) {
- body['sync_time_of_day'] = params.sync_time_of_day
- }
- if (params.primary_key_columns !== undefined) {
- body['primary_key_columns'] = params.primary_key_columns
- }
- if (params.cdc_table_mode !== undefined) {
- body['cdc_table_mode'] = params.cdc_table_mode
- }
- if (params.enabled_columns !== undefined) {
- body['enabled_columns'] = params.enabled_columns
- }
- if (params.row_filters !== undefined) {
- body['row_filters'] = params.row_filters
- }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/cancel/`,
- body,
})
return result
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json
index acaf51db5225..567fb6f27984 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-cancel.json
@@ -1,167 +1,9 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
- "cdc_table_mode": {
- "anyOf": [
- {
- "description": "* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both",
- "enum": ["consolidated", "cdc_only", "both"],
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both"
- },
- "enabled_columns": {
- "anyOf": [
- {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- {
- "type": "null"
- }
- ],
- "description": "Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here."
- },
"id": {
"description": "A UUID string identifying this external data schema.",
"type": "string"
- },
- "incremental_field": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "Column name used to track sync progress."
- },
- "incremental_field_lookback_seconds": {
- "anyOf": [
- {
- "maximum": 5184000,
- "minimum": 0,
- "type": "number"
- },
- {
- "type": "null"
- }
- ],
- "description": "Seconds to subtract from the stored incremental watermark at sync time, so each incremental run re-reads a rolling overlap window and catches late or backdated rows. Applies to timestamp/date incremental fields only. The stored watermark is unchanged. Maximum 5184000 (60 days)."
- },
- "incremental_field_type": {
- "anyOf": [
- {
- "description": "* `integer` - integer\n* `numeric` - numeric\n* `datetime` - datetime\n* `date` - date\n* `timestamp` - timestamp\n* `objectid` - objectid\n* `xid` - xid",
- "enum": ["integer", "numeric", "datetime", "date", "timestamp", "objectid", "xid"],
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "Data type of the incremental field.\n\n* `integer` - integer\n* `numeric` - numeric\n* `datetime` - datetime\n* `date` - date\n* `timestamp` - timestamp\n* `objectid` - objectid\n* `xid` - xid"
- },
- "primary_key_columns": {
- "anyOf": [
- {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- {
- "type": "null"
- }
- ],
- "description": "Column names for primary key deduplication."
- },
- "row_filters": {
- "anyOf": [
- {
- "items": {
- "properties": {
- "column": {
- "type": "string"
- },
- "operator": {
- "description": "One of: > >= < <= = != IN \"NOT IN\".",
- "type": "string"
- },
- "value": {
- "description": "Comparison value; must match the column's type. For `IN` / `NOT IN`, a comma-separated list (e.g. `1, 2, 3` or `'a','b'`)."
- }
- },
- "required": ["column", "operator", "value"],
- "type": "object"
- },
- "type": "array"
- },
- {
- "type": "null"
- }
- ],
- "description": "Predicates ANDed onto the source query so only matching rows sync. Each is `{column, operator, value}`; `null`/empty (default) syncs all rows. The operator must be one of `> >= < <= = != IN \"NOT IN\"` and the value must match the column's type (for `IN`/`NOT IN`, a comma-separated list like `1, 2, 3` or `'a','b'`). Applied on the next sync — not retroactive to already-synced rows."
- },
- "should_sync": {
- "type": "boolean"
- },
- "sync_frequency": {
- "anyOf": [
- {
- "description": "* `never` - never\n* `1min` - 1min\n* `5min` - 5min\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day",
- "enum": [
- "never",
- "1min",
- "5min",
- "15min",
- "30min",
- "1hour",
- "6hour",
- "12hour",
- "24hour",
- "7day",
- "30day"
- ],
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "How often to sync.\n\n* `never` - never\n* `1min` - 1min\n* `5min` - 5min\n* `15min` - 15min\n* `30min` - 30min\n* `1hour` - 1hour\n* `6hour` - 6hour\n* `12hour` - 12hour\n* `24hour` - 24hour\n* `7day` - 7day\n* `30day` - 30day"
- },
- "sync_time_of_day": {
- "anyOf": [
- {
- "pattern": "^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?$",
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "UTC time of day to run the sync (HH:MM:SS)."
- },
- "sync_type": {
- "anyOf": [
- {
- "description": "* `full_refresh` - full_refresh\n* `incremental` - incremental\n* `append` - append\n* `webhook` - webhook\n* `cdc` - cdc\n* `xmin` - xmin",
- "enum": ["full_refresh", "incremental", "append", "webhook", "cdc", "xmin"],
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "Sync strategy: incremental, full_refresh, append, cdc, or xmin.\n\n* `full_refresh` - full_refresh\n* `incremental` - incremental\n* `append` - append\n* `webhook` - webhook\n* `cdc` - cdc\n* `xmin` - xmin"
}
},
"required": ["id"],