: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(warehouse-sources): schedule full refreshes for incremental tables (#106146)
Daniel RCba72f48ed4be
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 35ed0bf52b10..2527246772aa 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -374,6 +374,7 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {},"ExternalDataSchema": {"should_sync": "enabled",+ "full_refresh_interval_days": "full refresh interval (days)",},"SignalScoutConfig": {"run_interval_minutes": "run interval (minutes)",@@ -944,6 +945,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {# second change on the entry that turns syncing on or off, which makes the schema# activity feed read "updated schema" in place of "enabled schema"."auto_disabled_at",+ # Derived from full_refresh_interval_days and moved by every full resync, so it is not user intent.+ "next_full_refresh_at",],"Evaluation": [# The fail-closed relation cannot be resolved outside a team scope; the handler diffs IDs instead.diff --git a/posthog/test/activity_logging/test_external_data_schema_activity_logging.py b/posthog/test/activity_logging/test_external_data_schema_activity_logging.pyindex 844705e87af1..1aa22e6578f2 100644--- a/posthog/test/activity_logging/test_external_data_schema_activity_logging.py+++ b/posthog/test/activity_logging/test_external_data_schema_activity_logging.py@@ -23,7 +23,8 @@ class TestExternalDataSchemaActivityLogging(ActivityLogTestHelper):self.assertIn("table", external_data_schema_exclusions)self.assertIn("destination_links", external_data_schema_exclusions)self.assertIn("auto_disabled_at", external_data_schema_exclusions)- self.assertEqual(len(external_data_schema_exclusions), 7)+ self.assertIn("next_full_refresh_at", external_data_schema_exclusions)+ self.assertEqual(len(external_data_schema_exclusions), 8)def test_external_data_schema_scope_in_activity_log_types(self):self.assertIn("ExternalDataSchema", get_args(ActivityScope))diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 27d45f8c14dc..5f09bc9a8b8e 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -1340,7 +1340,6 @@1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py-1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py1 products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py1 products/web_analytics/backend/hogql_queries/bot_definitions.pydiff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsxindex be9182cc90ae..8ad14f87051c 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx@@ -17,7 +17,7 @@ import {lemonToast,} from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { newInternalTab } from 'lib/utils/newInternalTab'@@ -50,6 +50,8 @@ import {defaultQuery,syncAnchorIntervalToHumanReadable,} from 'products/data_warehouse/frontend/utils'+import { externalDataSourcesBulkUpdateSchemasPartialUpdate } from 'products/warehouse_sources/frontend/generated/api'+import type { ExternalDataSchemaApi } from 'products/warehouse_sources/frontend/generated/api.schemas'import { ApiVersionDeprecationBanner } from '../SourceScene/SourceScene'import { ColumnSelectionPicker } from '../SourceScene/tabs/ColumnSelectionModal'@@ -871,6 +873,31 @@ function ColumnsAndRowFiltersSection({)}+const SCHEDULED_FULL_REFRESH_SYNC_TYPES: ExternalDataSourceSchema['sync_type'][] = ['incremental', 'append', 'xmin']+const MAX_FULL_REFRESH_INTERVAL_DAYS = 90+// A full refresh runs on a scheduled sync, so it cannot come around more often than the table syncs.+const MIN_FULL_REFRESH_DAYS_BY_FREQUENCY: Partial<Record<DataWarehouseSyncInterval, number>> = {+ '7day': 7,+ '30day': 30,+}++type ScheduleSectionSchema = ExternalDataSourceSchema &+ Partial<Pick<ExternalDataSchemaApi, 'full_refresh_interval_days' | 'next_full_refresh_at'>>++function fullRefreshDaysError(days: number | null, frequency: DataWarehouseSyncInterval): string | null {+ if (days === null) {+ return null+ }+ if (!Number.isInteger(days) || days < 1 || days > MAX_FULL_REFRESH_INTERVAL_DAYS) {+ return `Enter a whole number of days from 1 to ${MAX_FULL_REFRESH_INTERVAL_DAYS}, or leave it empty`+ }+ const minDays = MIN_FULL_REFRESH_DAYS_BY_FREQUENCY[frequency]+ if (minDays !== undefined && days < minDays) {+ return `A full refresh runs on a scheduled sync, so enter at least ${minDays} days, or sync more often`+ }+ return null+}+function ScheduleSection({sourceId,schema,@@ -878,12 +905,13 @@ function ScheduleSection({setIsProjectTime,}: {sourceId: string- schema: ExternalDataSourceSchema+ schema: ScheduleSectionSchemaisProjectTime: booleansetIsProjectTime: (v: boolean) => void}): JSX.Element {const { loadSchema } = useActions(schemaSceneLogic({ sourceId, schemaId: schema.id }))const isCdc = schema.sync_type === 'cdc'+ const supportsScheduledFullRefresh = SCHEDULED_FULL_REFRESH_SYNC_TYPES.includes(schema.sync_type)const frequencyOptions: LemonSelectOption<DataWarehouseSyncInterval>[] = allowedSyncFrequencies().map((value) => ({value,label: SyncFrequencyLabelMap[value],@@ -893,11 +921,15 @@ function ScheduleSection({schema.sync_frequency || (isCdc ? '5min' : '6hour'))const [draftSyncTimeOfDay, setDraftSyncTimeOfDay] = useState<string | null>(schema.sync_time_of_day ?? null)+ const [draftFullRefreshDays, setDraftFullRefreshDays] = useState<number | null>(+ schema.full_refresh_interval_days ?? null+ )const [saving, setSaving] = useState(false)const { disabledReason: accessDisabledReason } = useSchemaEditorAccess(schema)const serverFrequency = schema.sync_frequency || (isCdc ? '5min' : '6hour')const serverSyncTimeOfDay = schema.sync_time_of_day ?? null+ const serverFullRefreshDays = schema.full_refresh_interval_days ?? null// Reset the draft when the user navigates to a different schema or when the server values// change (e.g. after the sync type switches between CDC and non-CDC, which flips the default@@ -905,25 +937,35 @@ function ScheduleSection({useEffect(() => {setDraftFrequency(serverFrequency)setDraftSyncTimeOfDay(serverSyncTimeOfDay)- }, [schema.id, serverFrequency, serverSyncTimeOfDay])+ setDraftFullRefreshDays(serverFullRefreshDays)+ }, [schema.id, serverFrequency, serverSyncTimeOfDay, serverFullRefreshDays])- const isDirty = draftFrequency !== serverFrequency || draftSyncTimeOfDay !== serverSyncTimeOfDay+ const isDirty =+ draftFrequency !== serverFrequency ||+ draftSyncTimeOfDay !== serverSyncTimeOfDay ||+ draftFullRefreshDays !== serverFullRefreshDays+ const fullRefreshError = supportsScheduledFullRefresh+ ? fullRefreshDaysError(draftFullRefreshDays, draftFrequency)+ : nullconst handleSave = async (): Promise<void> => {setSaving(true)try {- await api.externalDataSources.bulkUpdateSchemas(sourceId, [- {- id: schema.id,- should_sync: schema.should_sync,- sync_type: schema.sync_type,- incremental_field: schema.incremental_field,- incremental_field_type: schema.incremental_field_type,- sync_frequency: draftFrequency,- sync_time_of_day: draftSyncTimeOfDay,- cdc_table_mode: schema.cdc_table_mode,- },- ])+ await externalDataSourcesBulkUpdateSchemasPartialUpdate(String(ApiConfig.getCurrentTeamId()), sourceId, {+ schemas: [+ {+ id: schema.id,+ should_sync: schema.should_sync,+ sync_type: schema.sync_type,+ incremental_field: schema.incremental_field,+ incremental_field_type: schema.incremental_field_type,+ sync_frequency: draftFrequency,+ sync_time_of_day: draftSyncTimeOfDay,+ cdc_table_mode: schema.cdc_table_mode,+ ...(supportsScheduledFullRefresh ? { full_refresh_interval_days: draftFullRefreshDays } : {}),+ },+ ],+ })lemonToast.success('Schedule saved')loadSchema()} catch (e: any) {@@ -963,13 +1005,21 @@ function ScheduleSection({isProjectTime={isProjectTime}setIsProjectTime={setIsProjectTime}/>+ {supportsScheduledFullRefresh && (+ <FullRefreshIntervalField+ schema={schema}+ draftFullRefreshDays={draftFullRefreshDays}+ setDraftFullRefreshDays={setDraftFullRefreshDays}+ isDraftSaved={draftFullRefreshDays === serverFullRefreshDays}+ />+ )}</div><div className="mt-4 flex justify-end"><LemonButtontype="primary"loading={saving}onClick={handleSave}- disabledReason={accessDisabledReason ?? (!isDirty ? 'No changes to save' : undefined)}+ disabledReason={accessDisabledReason ?? (!isDirty ? 'No changes to save' : fullRefreshError)}>Save</LemonButton>@@ -978,6 +1028,66 @@ function ScheduleSection({)}+function FullRefreshIntervalField({+ schema,+ draftFullRefreshDays,+ setDraftFullRefreshDays,+ isDraftSaved,+}: {+ schema: ScheduleSectionSchema+ draftFullRefreshDays: number | null+ setDraftFullRefreshDays: (value: number | null) => void+ isDraftSaved: boolean+}): JSX.Element {+ const { disabledReason: accessDisabledReason } = useSchemaEditorAccess(schema)++ return (+ <div className="flex flex-col gap-1">+ <span>Scheduled full refresh</span>+ <span className="text-xs text-muted max-w-md">+ Re-import every row of the table on this cadence, so rows deleted at the source are removed. The refresh+ runs on a scheduled sync, and queries keep showing the current rows until it finishes. Re-imported rows+ count toward your usage. Leave it empty to turn it off.+ {schema.sync_type === 'append' && (+ <span>+ {' '}+ For append only tables, a refresh replaces the rows collected so far with the rows the source+ has now.+ </span>+ )}+ </span>+ <div className="flex items-center gap-2">+ <LemonInput+ type="number"+ min={1}+ max={MAX_FULL_REFRESH_INTERVAL_DAYS}+ value={draftFullRefreshDays ?? NaN}+ onChange={(value) =>+ setDraftFullRefreshDays(value === undefined || Number.isNaN(value) ? null : value)+ }+ placeholder="Off"+ className="w-24"+ disabledReason={accessDisabledReason}+ data-attr="schema-full-refresh-interval-days"+ />+ <span>days</span>+ </div>+ {schema.next_full_refresh_at && isDraftSaved && (+ <span className="text-xs text-muted">+ Next full refresh:{' '}+ <TZLabel time={schema.next_full_refresh_at} formatDate="MMM DD, YYYY" formatTime="HH:mm" />+ </span>+ )}+ {draftFullRefreshDays !== null && (+ <LemonBanner type="warning" className="max-w-md">+ If workflows or destinations run on new rows of this table, each full refresh runs them again for+ every row.+ </LemonBanner>+ )}+ </div>+ )+}+function AnchorTimeField({schema,draftFrequency,diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.pyindex 4f30a05fe3bb..1b6a7bc14075 100644--- a/products/warehouse_sources/backend/facade/models.py+++ b/products/warehouse_sources/backend/facade/models.py@@ -31,6 +31,8 @@ from products.warehouse_sources.backend.models.external_data_job import ()from products.warehouse_sources.backend.models.external_data_schema import (CDC_SNAPSHOT_LANE_KEY,+ MAX_FULL_REFRESH_INTERVAL_DAYS,+ SCHEDULED_FULL_REFRESH_SYNC_TYPES,ExternalDataSchema,auto_enable_new_schemas,get_all_schemas_for_source_id,@@ -92,7 +94,9 @@ __all__ = ["MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND","MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND","MANAGED_WAREHOUSE_SOURCE_PREFIX",+ "MAX_FULL_REFRESH_INTERVAL_DAYS","PendingSourceCredential",+ "SCHEDULED_FULL_REFRESH_SYNC_TYPES","SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING","WarehouseColumnAnnotation","WarehouseColumnStatistics",diff --git a/products/warehouse_sources/backend/migrations/0168_externaldataschema_scheduled_full_refresh.py b/products/warehouse_sources/backend/migrations/0168_externaldataschema_scheduled_full_refresh.pynew file mode 100644index 000000000000..afba6fc24f76--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0168_externaldataschema_scheduled_full_refresh.py@@ -0,0 +1,35 @@+# Generated by Django 5.2.17 on 2026-09-24 16:10++import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0167_externaldatajob_running_idx"),+ ]++ operations = [+ migrations.AddField(+ model_name="externaldataschema",+ name="full_refresh_interval_days",+ field=models.SmallIntegerField(+ blank=True,+ help_text="Days between scheduled full refreshes. A full refresh re-imports every row, so rows deleted at the source are removed from the table. Null means no scheduled full refreshes.",+ null=True,+ validators=[+ django.core.validators.MinValueValidator(1),+ django.core.validators.MaxValueValidator(90),+ ],+ ),+ ),+ migrations.AddField(+ model_name="externaldataschema",+ name="next_full_refresh_at",+ field=models.DateTimeField(+ blank=True,+ help_text="When the next scheduled full refresh is due. The first scheduled sync that starts at most an hour before this time re-imports the table. Saving a new interval, or any full resync, moves it one interval ahead.",+ null=True,+ ),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 6844fa5205dd..b30eb7da0f5b 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0167_externaldatajob_running_idx+0168_externaldataschema_scheduled_full_refreshdiff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex cc205702fcfd..f12abc553d15 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -10,6 +10,7 @@ from datetime import UTC, date, datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, Optionalfrom django.conf import settings+from django.core.validators import MaxValueValidator, MinValueValidatorfrom django.db import models, transactionfrom django.utils import timezone@@ -95,6 +96,12 @@ def incremental_sync_blocked_reason(latest_error: str | None) -> str | None:# how long a rewrite nobody is advancing can pause a table's imports.REPARTITION_HOLD_MAX_AGE = timedelta(hours=48)+SCHEDULED_FULL_REFRESH_SYNC_TYPES = frozenset(+ {ExternalDataSchemaSyncType.INCREMENTAL, ExternalDataSchemaSyncType.APPEND, ExternalDataSchemaSyncType.XMIN}+)+MAX_FULL_REFRESH_INTERVAL_DAYS = 90+SCHEDULED_FULL_REFRESH_MAX_SLACK = timedelta(hours=1)+@dataclass(frozen=True, kw_only=True)class SyncDisableContext:@@ -271,6 +278,19 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField)sync_frequency_interval = models.DurationField(default=timedelta(hours=6), null=True, blank=True)sync_time_of_day = models.TimeField(null=True, blank=True, help_text="Time of day to run the sync (UTC)")+ full_refresh_interval_days = models.SmallIntegerField(+ null=True,+ blank=True,+ validators=[MinValueValidator(1), MaxValueValidator(MAX_FULL_REFRESH_INTERVAL_DAYS)],+ help_text="Days between scheduled full refreshes. A full refresh re-imports every row, so rows deleted "+ "at the source are removed from the table. Null means no scheduled full refreshes.",+ )+ next_full_refresh_at = models.DateTimeField(+ null=True,+ blank=True,+ help_text="When the next scheduled full refresh is due. The first scheduled sync that starts at most an hour "+ "before this time re-imports the table. Saving a new interval, or any full resync, moves it one interval ahead.",+ )initial_sync_complete = models.BooleanField(default=False)description = models.CharField(max_length=1000, null=True, blank=True)# null = sync all columns (default). Non-empty list = exact column projection.@@ -1052,6 +1072,26 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn str(value)return str(value)+ def restart_full_refresh_clock(self) -> None:+ if self.full_refresh_interval_days is None:+ self.next_full_refresh_at = None+ return+ self.next_full_refresh_at = timezone.now() + timedelta(days=self.full_refresh_interval_days)++ def scheduled_full_refresh_due(self) -> bool:+ if (+ self.full_refresh_interval_days is None+ or self.next_full_refresh_at is None+ or self.sync_type not in SCHEDULED_FULL_REFRESH_SYNC_TYPES+ ):+ return False+ # The wipe that restarts the clock lands a little after its tick, so without slack every refresh would+ # slip one tick later than the one before.+ slack = SCHEDULED_FULL_REFRESH_MAX_SLACK+ if self.sync_frequency_interval is not None:+ slack = min(slack, self.sync_frequency_interval / 2)+ return timezone.now() >= self.next_full_refresh_at - slack+def update_sync_type_config_for_reset_pipeline(self, *, clear_initial_sync_complete: bool = True) -> None:removes = ["reset_pipeline",@@ -1090,10 +1130,16 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField# Merged under the row lock rather than saved from this copy: the sync loaded it when it# started, and CDC capture writes the same JSON meanwhile (the snapshot marker among it).self.sync_type_config = update_sync_type_config_keys(- self.id, self.team_id, removes=removes, extra_model_fields=extra_model_fields+ self.id,+ self.team_id,+ removes=removes,+ extra_model_fields=extra_model_fields,+ restart_full_refresh_clock=True,)if clear_initial_sync_complete:self.initial_sync_complete = False+ # This copy still holds the due time, and a later full save of it would wipe the table again.+ self.restart_full_refresh_clock()def update_incremental_field_value(self, last_value: Any, save: bool = True, type: Literal["last"] | Literal["earliest"] = "last"@@ -1144,7 +1190,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldraise ValueError(f"Unsupported type for update_incremental_field_value: {type}")if save:- self.save(skip_activity_log=True)+ # A run calls this after every chunk with the copy it loaded at the start, so a full save would+ # put back settings the user changed during the run.+ self.save(update_fields=["sync_type_config", "updated_at"], skip_activity_log=True)def update_xmin_state(self, ceiling_xid: int, ceiling_xid8: int, num_wraparound: int, save: bool = True) -> None:# Call at job completion, not per-batch: a mid-run crash then re-reads the window@@ -1446,6 +1494,7 @@ def update_sync_type_config_keys(removes: Iterable[str] | None = None,mutate: Callable[[dict[str, Any]], None] | None = None,extra_model_fields: dict[str, Any] | None = None,+ restart_full_refresh_clock: bool = False,) -> dict[str, Any]:"""Atomically merge keys into a schema's `sync_type_config` under a row lock and return thepersisted config.@@ -1464,6 +1513,9 @@ def update_sync_type_config_keys(when a reset must flip both `sync_type_config` and another field (e.g. `initial_sync_complete`)atomically so no reader can observe the half-written state.+ `restart_full_refresh_clock` sets `next_full_refresh_at` from the locked row's interval, which may+ be newer than the caller's copy. The returned dict does not carry it.+Saves with `skip_activity_log=True`: `sync_type_config` is excluded from the schema's auditdiff anyway, and the bypass skips the extra `_get_before_update` SELECT that can fail when thepooler drops the connection mid-sync.@@ -1484,6 +1536,10 @@ def update_sync_type_config_keys(for field, value in extra_model_fields.items():setattr(schema, field, value)update_fields.append(field)+ if restart_full_refresh_clock:+ # From the locked row's interval, which may be newer than the caller's copy.+ schema.restart_full_refresh_clock()+ update_fields.append("next_full_refresh_at")schema.save(update_fields=update_fields, skip_activity_log=True)return configdiff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex 93c8ddaf5646..82ffb6ee6e78 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -44,6 +44,8 @@ from products.data_warehouse.backend.facade.api import ()from products.warehouse_sources.backend.facade.models import (CDC_SNAPSHOT_LANE_KEY,+ MAX_FULL_REFRESH_INTERVAL_DAYS,+ SCHEDULED_FULL_REFRESH_SYNC_TYPES,ExternalDataJob,ExternalDataSchema,ExternalDataSchemaDestination,@@ -209,6 +211,16 @@ NO_SYNC_FREQUENCY_ERROR = ("This table has no sync frequency, so its sync cannot be scheduled. Set a sync frequency first.")+SCHEDULED_FULL_REFRESH_SYNC_TYPE_ERROR = (+ "Scheduled full refreshes are only available for incremental, append only, and xmin syncs. "+ "Change the sync method first."+)++SCHEDULED_FULL_REFRESH_TOO_SHORT_ERROR = (+ "A full refresh runs on a scheduled sync, so the interval must be at least {days} days. "+ "Choose a longer interval, or sync more often."+)+def _trigger_schema_sync(instance: ExternalDataSchema) -> None:"""Trigger the schema's sync, creating its Temporal schedule first if it has none.@@ -394,6 +406,21 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializerssync_time_of_day = serializers.TimeField(required=False, allow_null=True, help_text="UTC time of day to run the sync (HH:MM:SS).")+ full_refresh_interval_days = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=1,+ max_value=MAX_FULL_REFRESH_INTERVAL_DAYS,+ help_text=(+ "Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the "+ "table and re-imports every row, so rows deleted at the source are removed. It runs on the first "+ "scheduled sync once the interval has passed, counted from when it was saved or from the last full "+ "resync, and can start up to an hour early. Queries keep returning the current rows until a full "+ "refresh finishes, and workflows and destinations that run on new rows of the table run again for "+ "every row. Available "+ "for incremental, append, and xmin syncs only, and never shorter than the sync frequency."+ ),+ )primary_key_columns = serializers.ListField(child=serializers.CharField(),required=False,@@ -501,6 +528,8 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"incremental_field_lookback_seconds","sync_frequency","sync_time_of_day",+ "full_refresh_interval_days",+ "next_full_refresh_at","description","primary_key_columns","cdc_table_mode",@@ -524,6 +553,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"latest_error","status","incremental_sync_blocked",+ "next_full_refresh_at","description","available_columns","source_column_metadata_available",@@ -1123,6 +1153,34 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersvalidated_data["sync_time_of_day"] = Noneinstance.sync_time_of_day = None+ # The schedule settings resend the interval on every save, so only a changed value restarts the clock.+ full_refresh_interval_days = validated_data.get(+ "full_refresh_interval_days", instance.full_refresh_interval_days+ )+ if full_refresh_interval_days is not None and resulting_sync_type not in SCHEDULED_FULL_REFRESH_SYNC_TYPES:+ requested_days = validated_data.get("full_refresh_interval_days")+ if requested_days is not None and requested_days != instance.full_refresh_interval_days:+ raise ValidationError({"full_refresh_interval_days": SCHEDULED_FULL_REFRESH_SYNC_TYPE_ERROR})+ full_refresh_interval_days = None+ if (+ full_refresh_interval_days is not None+ and ("full_refresh_interval_days" in validated_data or was_sync_frequency_updated)+ and instance.sync_frequency_interval is not None+ and dt.timedelta(days=full_refresh_interval_days) < instance.sync_frequency_interval+ ):+ raise ValidationError(+ {+ "full_refresh_interval_days": SCHEDULED_FULL_REFRESH_TOO_SHORT_ERROR.format(+ days=instance.sync_frequency_interval.days+ )+ }+ )+ if full_refresh_interval_days != instance.full_refresh_interval_days:+ instance.full_refresh_interval_days = full_refresh_interval_days+ instance.restart_full_refresh_clock()+ validated_data["full_refresh_interval_days"] = full_refresh_interval_days+ validated_data["next_full_refresh_at"] = instance.next_full_refresh_at+# A row can still carry a null interval from before that rejection. Turning the sync on, or# moving its time of day, rebuilds the schedule, which a null interval cannot do. Turning# the sync off only pauses the schedule, so it stays allowed.@@ -2058,6 +2116,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return Response(status=status.HTTP_200_OK)+ @extend_schema(request=None)@action(methods=["POST"], detail=True)def incremental_fields(self, request: Request, *args: Any, **kwargs: Any):instance: ExternalDataSchema = self.get_object()diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.pyindex 6d2388cac169..9818fe1a71e8 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py@@ -20,6 +20,7 @@ from posthog.permissions import is_service_authfrom products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resourcefrom products.data_warehouse.backend.facade.api import get_direct_query_engine, get_namespaced_resource_adapterfrom products.warehouse_sources.backend.facade.models import (+ MAX_FULL_REFRESH_INTERVAL_DAYS,ExternalDataSchema,ExternalDataSource,auto_enable_new_schemas,@@ -85,6 +86,18 @@ class ExternalDataSourceBulkUpdateSchemaSerializer(serializers.Serializer):allow_null=True,help_text="UTC anchor time for scheduled syncs.",)+ full_refresh_interval_days = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=1,+ max_value=MAX_FULL_REFRESH_INTERVAL_DAYS,+ help_text=(+ "Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the "+ "table and re-imports every row. Re-imported rows count toward usage, and workflows and destinations "+ "that run on new rows of the table run again for every row. Incremental, append, and xmin syncs only, "+ "and never shorter than the sync frequency."+ ),+ )primary_key_columns = serializers.ListField(child=serializers.CharField(),required=False,diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex f80801c9afd8..14cf8d8da889 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -1,5 +1,6 @@import reimport json+import uuidimport typingimport datetime as dtimport dataclasses@@ -12,7 +13,7 @@ from structlog.contextvars import bind_contextvarsfrom structlog.types import FilteringBoundLoggerfrom temporalio import activity, exceptions, workflowfrom temporalio.client import Client-from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.common import RetryPolicy, SearchAttributes, WorkflowIDReusePolicyfrom temporalio.exceptions import TimeoutType, WorkflowAlreadyStartedErrorfrom temporalio.workflow import ParentClosePolicy, start_child_workflow@@ -742,6 +743,13 @@ def trigger_schedule_buffer_one_activity(schedule_id: str) -> None:trigger_schedule_buffer_one(temporal, schedule_id)+def _started_by_own_schedule(search_attributes: SearchAttributes, schema_id: uuid.UUID | None) -> bool:+ # Temporal sets this on every run a schedule starts, manual triggers included. It comes from the start+ # event, so replay reads the same value.+ scheduled_by = search_attributes.get("TemporalScheduledById") or []+ return any(str(value) == str(schema_id) for value in scheduled_by)++# TODO: update retry policies## DETERMINISM: adding, removing, or reordering activities / child-workflow starts in `run` breaks@@ -845,6 +853,9 @@ class ExternalDataJobWorkflow(PostHogWorkflow):source_id=inputs.external_data_source_id,billable=inputs.billable,is_v3=is_v3,+ started_by_schedule=_started_by_own_schedule(+ workflow.info().search_attributes, inputs.external_data_schema_id+ ),)create_job_result = await workflow.execute_activity(@@ -864,6 +875,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):statistics_needed = Falseperson_property_sync_enabled = Falsefast_return_eligible = False+ scheduled_full_refresh = Falseelse:job_id = create_job_result.job_idincremental_or_append = create_job_result.incremental_or_append@@ -875,6 +887,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):statistics_needed = create_job_result.statistics_neededperson_property_sync_enabled = create_job_result.person_property_sync_enabledfast_return_eligible = create_job_result.fast_return_eligible+ scheduled_full_refresh = create_job_result.scheduled_full_refreshupdate_inputs.job_id = str(job_id) if job_id is not None else None# Check billing limits@@ -895,8 +908,9 @@ class ExternalDataJobWorkflow(PostHogWorkflow):# Pre-extraction, in-place repartition of any table flagged on a prior run. Runs here — sole# writer, lock held, before the merge — so the subsequent merge uses the memory-safe layout.- # A no-op unless a repartition is pending; never fails the sync (errors are swallowed).- if job_id is not None:+ # A no-op unless a repartition is pending; never fails the sync (errors are swallowed). A scheduled+ # full refresh deletes the table before extraction, so rewriting it first is wasted work.+ if job_id is not None and not scheduled_full_refresh:try:await workflow.execute_activity(maybe_repartition_table_activity,@@ -923,6 +937,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):source_id=inputs.external_data_source_id,reset_pipeline=inputs.reset_pipeline,fast_return_eligible=fast_return_eligible,+ scheduled_full_refresh=scheduled_full_refresh,)is_resumable_source = Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.pyindex 9108b9b10c87..bf49d70bf94d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py@@ -9,7 +9,7 @@ schema. The next run's pre-extraction activity performs the rewrite (see `repartfrom __future__ import annotationsimport asyncio-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Literalfrom django.conf import settingsfrom django.utils import timezone@@ -122,6 +122,45 @@ def is_repartition_hold_enabled(schema: ExternalDataSchema) -> bool:return is_schema_flag_enabled(schema, WAREHOUSE_REPARTITION_HOLD_FLAG)+def repartition_import_hold_reason(+ schema: ExternalDataSchema, logger: FilteringBoundLogger+) -> Literal["swap_staged", "rewrite_converging"] | None:+ """Why an in-flight repartition holds this schema's import, or None when it does not.++ Two situations hold the import. A staged swap holds it unconditionally, because the table's+ on-disk partition layout is mid-change and merging across that is data corruption, not staleness.+ A converging rewrite holds it only when the schema opted in and its checkpoint is fresh enough to+ be worth waiting for; the flag is checked second so a schema without it never pays for the+ evaluation, and a flag lookup that throws leaves the import running — pausing a customer's+ ingestion is the more expensive way to be wrong.++ Side-effect free, because the scheduled full refresh defers on the same answer. The two must not+ drift: a refresh run skips the repartition activity, so a refresh that proceeds while the import+ is held never wipes the table.+ """+ swap = schema.repartition_swap+ if swap and swap.get("state") == "ready":+ # The rewrite may already have re-bucketed the data in S3 while the schema row still holds the+ # old settings. The merge computes each row's `_ph_partition_key` from those settings and+ # scopes its predicate to `target._ph_partition_key = '<partition>'`, so under that mismatch+ # nothing matches and every fetched row inserts instead of upserting — the whole incremental+ # lookback window duplicated, with the job still reporting Completed. The repartition activity+ # runs ahead of the import on every sync and resolves the marker, so waiting costs one run's+ # freshness. Not behind the hold rollout flag: that flag trades freshness for a rewrite that+ # can finish, and this trades it for not corrupting the table.+ return "swap_staged"++ if not schema.repartition_holds_import:+ return None+ try:+ if not is_repartition_hold_enabled(schema):+ return None+ except Exception:+ logger.warning("Could not evaluate the repartition hold flag; importing", exc_info=True)+ return None+ return "rewrite_converging"++def base_event_props(schema: ExternalDataSchema, source: ExternalDataSource, job_id: str | None) -> dict[str, Any]:return {"team_id": schema.team_id,diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.pyindex 72e7295da167..a21ea4eb2442 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_jobCreateSourceTemplateInputs,ExternalDataJobWorkflow,UpdateExternalDataJobStatusInputs,+ _started_by_own_schedule,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResultfrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (@@ -53,6 +54,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie)_JOB_ID = "01960000-0000-0000-0000-000000000000"+_SCHEMA_ID = uuid.UUID("01960000-0000-0000-0000-000000000001")def _stub_activities(@@ -63,6 +65,7 @@ def _stub_activities(skip_post_import_activities: bool = False,fast_return_eligible: bool = False,source_has_new_data: bool = True,+ scheduled_full_refresh: bool = False,) -> list:@activity.defn(name="check_pipeline_version_activity")async def check_pipeline_version(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:@@ -92,6 +95,7 @@ def _stub_activities(statistics_needed=True,person_property_sync_enabled=True,fast_return_eligible=fast_return_eligible,+ scheduled_full_refresh=scheduled_full_refresh,)@activity.defn(name="check_billing_limits_activity")@@ -106,6 +110,8 @@ def _stub_activities(@activity.defn(name="import_data_activity_sync")async def import_data(inputs: ImportDataActivityInputs) -> PipelineResult:executed.append("import_data_activity_sync")+ if inputs.scheduled_full_refresh:+ executed.append("import_data_activity_sync:scheduled_full_refresh")if inputs.fast_return_eligible and not source_has_new_data:return PipelineResult(should_trigger_cdp_producer=False,@@ -151,6 +157,7 @@ async def _run_workflow(skip_post_import_activities: bool = False,fast_return_eligible: bool = False,source_has_new_data: bool = True,+ scheduled_full_refresh: bool = False,) -> tuple[list[str], list[str]]:"""Run the workflow with stubbed activities; return (executed activities + child starts inorder, started child ids)."""@@ -181,6 +188,7 @@ async def _run_workflow(skip_post_import_activities=skip_post_import_activities,fast_return_eligible=fast_return_eligible,source_has_new_data=source_has_new_data,+ scheduled_full_refresh=scheduled_full_refresh,),workflow_runner=UnsandboxedWorkflowRunner(),activity_executor=ThreadPoolExecutor(max_workers=10),@@ -288,6 +296,29 @@ async def test_fast_return_skips_post_import_only_when_the_source_is_unchanged(assert "create_source_templates" in executed[email protected]("scheduled_full_refresh", [True, False])+async def test_the_import_learns_a_run_is_a_scheduled_full_refresh(scheduled_full_refresh: bool):+ executed, _ = await _run_workflow(+ is_v3=False, consumer_manages_job_status=False, scheduled_full_refresh=scheduled_full_refresh+ )++ assert ("import_data_activity_sync:scheduled_full_refresh" in executed) is scheduled_full_refresh+ assert ("maybe_repartition_table_activity" in executed) is not scheduled_full_refresh+++ "search_attributes,expected",+ [+ pytest.param({"TemporalScheduledById": [str(_SCHEMA_ID)]}, True, id="own_schedule"),+ pytest.param({"TemporalScheduledById": [str(uuid.uuid4())]}, False, id="another_schedule"),+ pytest.param({}, False, id="started_directly"),+ ],+)+def test_only_the_schemas_own_schedule_counts_as_scheduled(search_attributes: dict, expected: bool):+ assert _started_by_own_schedule(search_attributes, _SCHEMA_ID) is expected++@pytest.mark.asyncio@pytest.mark.parametrize("steps_mode",diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex 8f77d09d362d..1300f0f121b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -40,6 +40,9 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (retry_on_operational_error,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (+ repartition_import_hold_reason,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (get_v3_pipeline_lock_holder,)@@ -216,13 +219,15 @@ def _create_job(# TODO: remove dependency[email protected](frozen=True)class CreateExternalDataJobModelActivityInputs:team_id: intschema_id: uuid.UUIDsource_id: uuid.UUIDbillable: boolis_v3: bool = False+ # Admin resyncs and non-billable resumes start the workflow directly and must not become a full refresh.+ started_by_schedule: bool = False@propertydef properties_to_log(self) -> dict[str, typing.Any]:@@ -314,6 +319,9 @@ class CreateExternalDataJobModelActivityOutputs:# Computed here because this activity already resolves the repair gates the decision needs.# Defaults False so a payload from a worker that predates the field takes the full path.fast_return_eligible: bool = False+ # The workflow hands this to the import, which resets only while the schema is still due. Nothing is+ # stored on the schema, so a run that stops before the wipe leaves no reset behind for later runs.+ scheduled_full_refresh: bool = False@activity.defn@@ -350,13 +358,27 @@ def create_external_data_job_model_activity(inputs.team_id, source.source_type):destination_ids = destination_ids_for_run(schema)+ # A refresh run skips the repartition activity, the only thing that ends a repartition hold on+ # the import. A refresh while the import is held never wipes the table or restarts the clock,+ # so the refresh waits until the repartition resolves.+ scheduled_full_refresh = (+ inputs.started_by_schedule+ and not schema.reset_pipeline+ and schema.scheduled_full_refresh_due()+ and repartition_import_hold_reason(schema, logger) is None+ )+ schema_snapshot = _build_schema_snapshot(schema)+ if scheduled_full_refresh:+ schema_snapshot["scheduled_full_refresh"] = True+ logger.info("This sync is a scheduled full refresh. It re-imports every row of the table.")+job = _create_job(team_id=inputs.team_id,source_id=inputs.source_id,schema_id=inputs.schema_id,pipeline_version=pipeline_version,billable=inputs.billable,- schema_snapshot=_build_schema_snapshot(schema),+ schema_snapshot=schema_snapshot,destination_ids=destination_ids,)# Persist the Running status only after the job row exists: a Running schema with no job@@ -402,7 +424,7 @@ def create_external_data_job_model_activity(# customer_analytics via external_product_hooks; not imported here).person_property_sync_enabled = person_property_sync_enabled_for(inputs.team_id, schema_binding(schema.id))- fast_return_eligible = _fast_return_eligible(+ fast_return_eligible = not scheduled_full_refresh and _fast_return_eligible(schema=schema,team_id=inputs.team_id,enrichment_needed=enrichment_needed,@@ -422,6 +444,7 @@ def create_external_data_job_model_activity(statistics_needed=statistics_needed,person_property_sync_enabled=person_property_sync_enabled,fast_return_eligible=fast_return_eligible,+ scheduled_full_refresh=scheduled_full_refresh,)except V3PipelineLockLostError:# The takeover race the guard handles, not a defect — skip the generic handler'sdiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex a6f549e52d14..792c42f29b54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -51,7 +51,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller import (capture_repartition_event,- is_repartition_hold_enabled,+ repartition_import_hold_reason,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResultfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import PipelineInputs@@ -109,6 +109,8 @@ class ImportDataActivityInputs:# a cursor, is past its initial sync, and owes no repair work, so a negative probe may# complete this run without extracting. Defaults False so old payloads keep the full path.fast_return_eligible: bool = False+ # Kept apart from `reset_pipeline`, which every retry would read again and wipe the table again.+ scheduled_full_refresh: bool = False@propertydef properties_to_log(self) -> dict[str, Any]:@@ -119,9 +121,20 @@ class ImportDataActivityInputs:"run_id": self.run_id,"reset_pipeline": self.reset_pipeline,"fast_return_eligible": self.fast_return_eligible,+ "scheduled_full_refresh": self.scheduled_full_refresh,}+def _resolve_reset_pipeline(inputs: ImportDataActivityInputs, schema: ExternalDataSchema) -> bool:+ if inputs.reset_pipeline is not None:+ return inputs.reset_pipeline+ if schema.sync_type_config.get("reset_pipeline", False) is True:+ return True+ # Each attempt loads the schema again, and the first wipe moves the due time a full interval ahead, so a+ # retry after the wipe carries on with the re-import instead of wiping it again.+ return inputs.scheduled_full_refresh and schema.scheduled_full_refresh_due()++@database_sync_to_async_pooldef _get_external_data_job(run_id: str) -> ExternalDataJob:return ExternalDataJob.objects.prefetch_related(@@ -223,28 +236,13 @@ async def _warehouse_parent_reuse_available(def _import_held_for_repartition(schema: ExternalDataSchema | None, logger: FilteringBoundLogger) -> bool:- """Whether an in-flight repartition should pause this schema's import for one run.-- Two situations hold the import. A staged swap holds it unconditionally, because the table's- on-disk partition layout is mid-change and merging across that is data corruption, not staleness.- A converging rewrite holds it only when the schema opted in and its checkpoint is fresh enough to- be worth waiting for; the flag is checked second so a schema without it never pays for the- evaluation, and a flag lookup that throws leaves the import running — pausing a customer's- ingestion is the more expensive way to be wrong.- """+ """Whether an in-flight repartition should pause this schema's import for one run."""if schema is None:return False- swap = schema.repartition_swap- if swap and swap.get("state") == "ready":- # The rewrite may already have re-bucketed the data in S3 while the schema row still holds the- # old settings. The merge computes each row's `_ph_partition_key` from those settings and- # scopes its predicate to `target._ph_partition_key = '<partition>'`, so under that mismatch- # nothing matches and every fetched row inserts instead of upserting — the whole incremental- # lookback window duplicated, with the job still reporting Completed. The repartition activity- # runs ahead of this one on every sync and resolves the marker, so waiting costs one run's- # freshness. Not behind the hold rollout flag: that flag trades freshness for a rewrite that- # can finish, and this trades it for not corrupting the table.+ reason = repartition_import_hold_reason(schema, logger)+ if reason == "swap_staged":+ swap = schema.repartition_swap or {}logger.warning("Holding import: a repartition swap is staged, so the table's partition layout is mid-change",schema_id=str(schema.id),@@ -261,34 +259,28 @@ def _import_held_for_repartition(schema: ExternalDataSchema | None, logger: Filt)return True- if not schema.repartition_holds_import:- return False- try:- if not is_repartition_hold_enabled(schema):- return False- except Exception:- logger.warning("Could not evaluate the repartition hold flag; importing", exc_info=True)- return False+ if reason == "rewrite_converging":+ rewrite = schema.repartition_rewrite or {}+ logger.info(+ "Holding import: a repartition rewrite is converging on this table",+ schema_id=str(schema.id),+ rows_written=rewrite.get("rows_written"),+ held_at=rewrite.get("held_at"),+ )+ capture_repartition_event(+ "warehouse_repartition_import_held",+ {+ "team_id": schema.team_id,+ "schema_id": str(schema.id),+ "resource_name": schema.name,+ "reason": "rewrite_converging",+ "rows_written": rewrite.get("rows_written"),+ "held_at": rewrite.get("held_at"),+ },+ )+ return True- rewrite = schema.repartition_rewrite or {}- logger.info(- "Holding import: a repartition rewrite is converging on this table",- schema_id=str(schema.id),- rows_written=rewrite.get("rows_written"),- held_at=rewrite.get("held_at"),- )- capture_repartition_event(- "warehouse_repartition_import_held",- {- "team_id": schema.team_id,- "schema_id": str(schema.id),- "resource_name": schema.name,- "reason": "rewrite_converging",- "rows_written": rewrite.get("rows_written"),- "held_at": rewrite.get("held_at"),- },- )- return True+ return Falseasync def _probe_found_new_data(@@ -435,19 +427,16 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:schema: ExternalDataSchema | None = model.schemaassert schema is not None- if inputs.reset_pipeline is not None:- reset_pipeline = inputs.reset_pipeline- else:- reset_pipeline = schema.sync_type_config.get("reset_pipeline", False) is True-- await logger.adebug(f"schema.sync_type_config = {schema.sync_type_config}")- await logger.adebug(f"reset_pipeline = {reset_pipeline}")-try:schema = await _get_external_data_schema(inputs.schema_id, inputs.team_id)except ExternalDataSchema.DoesNotExist as e:await _handle_import_error(job_inputs, logger, e)+ reset_pipeline = _resolve_reset_pipeline(inputs, schema)++ await logger.adebug(f"schema.sync_type_config = {schema.sync_type_config}")+ await logger.adebug(f"reset_pipeline = {reset_pipeline}")+processed_incremental_last_value = Noneprocessed_incremental_earliest_value = None# The cursor as stored, before the lookback shift below moves it back.diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.pyindex fb0f34ae6b4b..633a1dc758d8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie)MODULE = "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model"+CONTROLLER_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"DB_RETRY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"@@ -301,6 +302,92 @@ class TestCreateJobActivityStatusOrdering:assert schema.status == ExternalDataSchema.Status.FAILED+class TestCreateJobActivityScheduledFullRefresh:+ @parameterized.expand(+ [+ ("due_on_a_scheduled_run", True, dt.timedelta(days=-1), {}, False, True),+ ("due_on_a_directly_started_run", False, dt.timedelta(days=-1), {}, False, False),+ ("not_yet_due", True, dt.timedelta(days=1), {}, False, False),+ (+ "due_with_a_staged_repartition_swap",+ True,+ dt.timedelta(days=-1),+ {"repartition_swap": {"state": "ready", "temp_uri": "s3://temp", "live_uri": "s3://live"}},+ False,+ False,+ ),+ (+ "due_with_a_held_repartition_rewrite",+ True,+ dt.timedelta(days=-1),+ {"repartition_rewrite": {"temp_uri": "s3://temp", "rows_written": 10}},+ True,+ False,+ ),+ (+ "due_with_a_rewrite_while_the_hold_flag_is_off",+ True,+ dt.timedelta(days=-1),+ {"repartition_rewrite": {"temp_uri": "s3://temp", "rows_written": 10}},+ False,+ True,+ ),+ (+ "due_with_a_queued_repartition",+ True,+ dt.timedelta(days=-1),+ {"repartition_pending": {"partition_mode": "datetime", "partition_keys": ["created_at"]}},+ False,+ True,+ ),+ ]+ )+ @patch(f"{MODULE}.close_old_connections")+ @patch(f"{MODULE}.activity")+ def test_only_a_due_scheduled_run_becomes_a_full_refresh(+ self,+ _name: str,+ started_by_schedule: bool,+ due_in: dt.timedelta,+ repartition_config: dict,+ hold_flag_enabled: bool,+ expect_refresh: bool,+ mock_activity: MagicMock,+ _mock_close_connections: MagicMock,+ ) -> None:+ mock_activity.info.return_value.workflow_id = "wf-1"+ mock_activity.info.return_value.workflow_run_id = "run-1"+ team = _team()+ schema = _schema(team, None)+ schema.sync_type = ExternalDataSchema.SyncType.INCREMENTAL+ schema.full_refresh_interval_days = 7+ schema.next_full_refresh_at = timezone.now() + due_in+ config = {**(schema.sync_type_config or {}), **repartition_config}+ if "repartition_rewrite" in config:+ config["repartition_rewrite"] = {**config["repartition_rewrite"], "held_at": timezone.now().isoformat()}+ schema.sync_type_config = config+ schema.save()++ with patch(f"{CONTROLLER_MODULE}.is_repartition_hold_enabled", return_value=hold_flag_enabled):+ result = create_external_data_job_model_activity(+ CreateExternalDataJobModelActivityInputs(+ team_id=team.id,+ schema_id=schema.id,+ source_id=schema.source_id,+ billable=True,+ started_by_schedule=started_by_schedule,+ )+ )++ schema.refresh_from_db()+ snapshot = ExternalDataJob.objects.get(schema_id=schema.id).schema_snapshot+ assert snapshot is not None+ assert result.scheduled_full_refresh is expect_refresh+ assert snapshot.get("scheduled_full_refresh", False) is expect_refresh+ assert schema.reset_pipeline is False++@pytest.mark.django_dbclass TestCreateJobActivityDeletedSourceOrSchema:# Deleting a source or a schema cancels its schedule, but a run Temporal already started stilldiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 7efaea3cfaad..b726e6b44bf9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -1,7 +1,7 @@import uuidimport contextlibimport dataclasses-from datetime import datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, castimport pytest@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_jobNEW_TABLE_NOT_READY_MESSAGE,_transient_error_message,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import repartition_controllerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (SchemaColumnTypeChangedException,)@@ -50,6 +51,7 @@ from products.warehouse_sources.backend.temporal.data_imports.util import (from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import import_data_sync as modulefrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (ImportDataActivityInputs,+ _resolve_reset_pipeline,import_data_activity_sync,)from products.warehouse_sources.backend.types import IncrementalFieldType@@ -1357,9 +1359,37 @@ def test_a_staged_repartition_swap_holds_the_import_whatever_the_rollout_flag_sawith (mock.patch.object(module, "capture_repartition_event"),- mock.patch.object(module, "is_repartition_hold_enabled", return_value=False) as flag,+ mock.patch.object(repartition_controller, "is_repartition_hold_enabled", return_value=False) as flag,):held = module._import_held_for_repartition(schema, mock.MagicMock())assert held is expectedflag.assert_not_called()+++ "scheduled_full_refresh,due_in_days,expected",+ [+ pytest.param(True, -1, True, id="first_attempt_of_a_due_refresh"),+ pytest.param(True, 7, False, id="retry_after_the_wipe_moved_the_due_time"),+ pytest.param(False, -1, False, id="run_not_marked_as_a_refresh"),+ ],+)+def test_a_scheduled_full_refresh_resets_only_while_the_schema_is_due(+ scheduled_full_refresh: bool, due_in_days: int, expected: bool+) -> None:+ schema = ExternalDataSchema(+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={},+ full_refresh_interval_days=7,+ next_full_refresh_at=datetime.now(UTC) + timedelta(days=due_in_days),+ )+ inputs = ImportDataActivityInputs(+ team_id=1,+ schema_id=uuid.uuid4(),+ source_id=uuid.uuid4(),+ run_id="run",+ scheduled_full_refresh=scheduled_full_refresh,+ )++ assert _resolve_reset_pipeline(inputs, schema) is expecteddiff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.pyindex 2da8a4bb55ca..31794d715089 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py@@ -1,9 +1,10 @@import uuidimport contextlib-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest import mock@@ -1657,6 +1658,122 @@ class TestExternalDataSchema(APIBaseTest):mock_sync_workflow.assert_called_once()assert mock_sync_workflow.call_args.kwargs["create"] is True+ @parameterized.expand(+ [+ (+ "enabling_starts_the_clock",+ ExternalDataSchema.SyncType.INCREMENTAL,+ None,+ {"full_refresh_interval_days": 7},+ 200,+ (7, datetime(2026, 10, 1, 12, tzinfo=UTC)),+ ),+ (+ "changing_the_interval_restarts_the_clock",+ ExternalDataSchema.SyncType.INCREMENTAL,+ 7,+ {"full_refresh_interval_days": 3},+ 200,+ (3, datetime(2026, 9, 27, 12, tzinfo=UTC)),+ ),+ (+ "resaving_the_same_interval_keeps_the_clock",+ ExternalDataSchema.SyncType.INCREMENTAL,+ 7,+ {"full_refresh_interval_days": 7, "sync_time_of_day": "05:00:00"},+ 200,+ (7, datetime(2026, 9, 26, tzinfo=UTC)),+ ),+ (+ "clearing_the_interval_clears_the_clock",+ ExternalDataSchema.SyncType.INCREMENTAL,+ 7,+ {"full_refresh_interval_days": None},+ 200,+ (None, None),+ ),+ (+ "switching_to_full_refresh_turns_it_off",+ ExternalDataSchema.SyncType.INCREMENTAL,+ 7,+ {"sync_type": "full_refresh"},+ 200,+ (None, None),+ ),+ (+ "switching_to_full_refresh_with_the_saved_interval_resent_turns_it_off",+ ExternalDataSchema.SyncType.INCREMENTAL,+ 7,+ {"sync_type": "full_refresh", "full_refresh_interval_days": 7},+ 200,+ (None, None),+ ),+ (+ "a_full_refresh_table_rejects_it",+ ExternalDataSchema.SyncType.FULL_REFRESH,+ None,+ {"full_refresh_interval_days": 7},+ 400,+ (None, None),+ ),+ (+ "an_interval_shorter_than_the_sync_frequency_is_rejected",+ ExternalDataSchema.SyncType.INCREMENTAL,+ None,+ {"full_refresh_interval_days": 3, "sync_frequency": "7day"},+ 400,+ (None, None),+ ),+ (+ "a_sync_frequency_longer_than_the_interval_is_rejected",+ ExternalDataSchema.SyncType.INCREMENTAL,+ 3,+ {"sync_frequency": "7day"},+ 400,+ (3, datetime(2026, 9, 26, tzinfo=UTC)),+ ),+ ]+ )+ def test_full_refresh_interval_schedules_the_next_full_refresh(+ self,+ _name: str,+ sync_type: str,+ initial_days: int | None,+ payload: dict[str, Any],+ expected_status: int,+ expected: tuple[int | None, datetime | None],+ ) -> None:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=ExternalDataSourceType.POSTGRES,+ job_inputs={"host": "h", "port": 5432, "database": "d", "user": "u", "password": "p", "schema": "public"},+ )+ schema = ExternalDataSchema.objects.create(+ name="public.orders",+ team=self.team,+ source=source,+ should_sync=False,+ sync_type=sync_type,+ sync_type_config={"incremental_field": "updated_at", "incremental_field_type": "timestamp"},+ full_refresh_interval_days=initial_days,+ next_full_refresh_at=datetime(2026, 9, 26, tzinfo=UTC) if initial_days else None,+ )++ with (+ time_machine.travel(datetime(2026, 9, 24, 12, tzinfo=UTC), tick=False),+ mock.patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",+ return_value=False,+ ),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}", data=payload, format="json"+ )++ assert response.status_code == expected_status, response.content+ schema.refresh_from_db()+ assert (schema.full_refresh_interval_days, schema.next_full_refresh_at) == expected+def test_update_schema_enable_should_sync_rejects_cdc_without_primary_key(self):# Schemas already in CDC mode with an empty primary_key_columns (created before the# API gate landed) must not be re-enabled until a PK is added on the source side.diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 0eeb3716e7e2..46c43206f849 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -1218,6 +1218,33 @@ class TestExternalDataSource(APIBaseTest):schema.refresh_from_db()assert schema.sync_type_config.get("primary_key_columns") == ["id"]+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",+ return_value=False,+ )+ def test_bulk_update_schemas_sets_full_refresh_interval(self, _mock_workflow_exists):+ source = self._create_external_data_source()+ schema = ExternalDataSchema.objects.create(+ name="Customers",+ team_id=self.team.pk,+ source=source,+ should_sync=True,+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "updated_at", "incremental_field_type": "datetime"},+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/bulk_update_schemas",+ data={"schemas": [{"id": str(schema.id), "full_refresh_interval_days": 7}]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()[0]["full_refresh_interval_days"] == 7+ schema.refresh_from_db()+ assert schema.full_refresh_interval_days == 7+ assert schema.next_full_refresh_at is not None+@patch("products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",return_value=True,@@ -3105,6 +3132,8 @@ class TestExternalDataSource(APIBaseTest):"table": schema.table,"sync_frequency": sync_frequency_interval_to_sync_frequency(schema.sync_frequency_interval),"sync_time_of_day": schema.sync_time_of_day,+ "full_refresh_interval_days": None,+ "next_full_refresh_at": None,"description": schema.description,"primary_key_columns": None,"cdc_table_mode": "consolidated",diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 50b183bf35ed..ea7f56742de3 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -5,6 +5,7 @@ from datetime import UTC, date, datetime, timedeltafrom typing import Anyimport pytest+import time_machinefrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -1103,6 +1104,82 @@ def test_reset_pipeline_preserves_partition_mode_override() -> None:assert schema.partition_format == "month"+class TestRunSavesKeepTheFullRefreshInterval(BaseTest):+ def test_a_cursor_save_keeps_an_interval_saved_during_the_run(self) -> None:+ source = ExternalDataSource.objects.create(team=self.team, source_type="Postgres", job_inputs={})+ created = ExternalDataSchema.objects.create(+ name="orders",+ team=self.team,+ source=source,+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"incremental_field": "id", "incremental_field_type": IncrementalFieldType.Integer},+ full_refresh_interval_days=7,+ )+ run_copy = ExternalDataSchema.objects.get(pk=created.pk)+ ExternalDataSchema.objects.filter(pk=created.pk).update(full_refresh_interval_days=3)++ run_copy.update_incremental_field_value(42)++ created.refresh_from_db()+ assert created.full_refresh_interval_days == 3+ assert created.sync_type_config["incremental_field_last_value"] == 42++ def test_the_clock_restarts_from_the_interval_saved_during_the_run(self) -> None:+ source = ExternalDataSource.objects.create(team=self.team, source_type="Postgres", job_inputs={})+ created = ExternalDataSchema.objects.create(+ name="orders",+ team=self.team,+ source=source,+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ sync_type_config={"reset_pipeline": True},+ full_refresh_interval_days=7,+ next_full_refresh_at=datetime(2026, 9, 22, 3, 0, tzinfo=UTC),+ )+ run_copy = ExternalDataSchema.objects.get(pk=created.pk)+ ExternalDataSchema.objects.filter(pk=created.pk).update(full_refresh_interval_days=3)++ with time_machine.travel(datetime(2026, 9, 22, 3, 10, tzinfo=UTC), tick=False):+ run_copy.update_sync_type_config_for_reset_pipeline()+ assert run_copy.scheduled_full_refresh_due() is False++ created.refresh_from_db()+ assert (created.full_refresh_interval_days, created.next_full_refresh_at) == (+ 3,+ datetime(2026, 9, 25, 3, 10, tzinfo=UTC),+ )+++class TestScheduledFullRefreshDue:+ def _schema(self, sync_type: str, sync_frequency_interval: timedelta) -> ExternalDataSchema:+ return ExternalDataSchema(+ sync_type=sync_type,+ sync_frequency_interval=sync_frequency_interval,+ full_refresh_interval_days=7,+ next_full_refresh_at=datetime(2026, 9, 22, 3, 10, tzinfo=UTC),+ )++ @parameterized.expand(+ [+ ("daily_tick_just_before_the_due_time", timedelta(days=1), datetime(2026, 9, 22, 3, 0, 5), True),+ ("daily_tick_a_day_early", timedelta(days=1), datetime(2026, 9, 21, 3, 0, 5), False),+ ("half_hourly_tick_just_before_the_due_time", timedelta(minutes=30), datetime(2026, 9, 22, 3, 0, 5), True),+ ("half_hourly_tick_one_cadence_early", timedelta(minutes=30), datetime(2026, 9, 22, 2, 30, 5), False),+ ]+ )+ def test_due_on_the_tick_nearest_the_due_time(+ self, _name: str, sync_frequency_interval: timedelta, now: datetime, expected: bool+ ) -> None:+ schema = self._schema(ExternalDataSchema.SyncType.INCREMENTAL, sync_frequency_interval)+ with time_machine.travel(now.replace(tzinfo=UTC), tick=False):+ assert schema.scheduled_full_refresh_due() is expected++ @parameterized.expand([("full_refresh", "full_refresh"), ("cdc", "cdc"), ("webhook", "webhook")])+ def test_never_due_for_a_sync_type_that_rereads_or_streams(self, _name: str, sync_type: str) -> None:+ schema = self._schema(sync_type, timedelta(days=1))+ with time_machine.travel(datetime(2026, 10, 1, tzinfo=UTC), tick=False):+ assert schema.scheduled_full_refresh_due() is False++def test_set_partitioning_enabled_consumes_partition_mode_override() -> None:schema = ExternalDataSchema(sync_type_config={"partition_mode_override": "datetime", "partitioning_keys_override": ["action_date"]}diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 27d4806b0437..122eceac3f45 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -339,6 +339,18 @@ export interface ExternalDataSchemaApi {* @nullable*/sync_time_of_day?: string | null+ /**+ * Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency.+ * @minimum 1+ * @maximum 90+ * @nullable+ */+ full_refresh_interval_days?: number | null+ /**+ * When the next scheduled full refresh is due. The first scheduled sync that starts at most an hour before this time re-imports the table. Saving a new interval, or any full resync, moves it one interval ahead.+ * @nullable+ */+ readonly next_full_refresh_at: string | null/** @nullable */readonly description: string | null/**@@ -507,6 +519,18 @@ export interface PatchedExternalDataSchemaApi {* @nullable*/sync_time_of_day?: string | null+ /**+ * Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency.+ * @minimum 1+ * @maximum 90+ * @nullable+ */+ full_refresh_interval_days?: number | null+ /**+ * When the next scheduled full refresh is due. The first scheduled sync that starts at most an hour before this time re-imports the table. Saving a new interval, or any full resync, moves it one interval ahead.+ * @nullable+ */+ readonly next_full_refresh_at?: string | null/** @nullable */readonly description?: string | null/**@@ -4960,6 +4984,13 @@ export interface ExternalDataSourceBulkUpdateSchemaApi {* @nullable*/sync_time_of_day?: string | null+ /**+ * Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row. Re-imported rows count toward usage, and workflows and destinations that run on new rows of the table run again for every row. Incremental, append, and xmin syncs only, and never shorter than the sync frequency.+ * @minimum 1+ * @maximum 90+ * @nullable+ */+ full_refresh_interval_days?: number | null/*** Column names for primary key deduplication.* @nullablediff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.tsindex d82584513470..5235ab64d314 100644--- a/products/warehouse_sources/frontend/generated/api.ts+++ b/products/warehouse_sources/frontend/generated/api.ts@@ -400,14 +400,11 @@ export const getExternalDataSchemasIncrementalFieldsCreateUrl = (projectId: striexport const externalDataSchemasIncrementalFieldsCreate = async (projectId: string,id: string,- externalDataSchemaApi?: NonReadonly<ExternalDataSchemaApi>,options?: RequestInit): Promise<void> => {return apiMutator<void>(getExternalDataSchemasIncrementalFieldsCreateUrl(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.tsindex cac69eb80ce6..d1824e5b6e5d 100644--- a/products/warehouse_sources/frontend/generated/api.zod.ts+++ b/products/warehouse_sources/frontend/generated/api.zod.ts@@ -119,6 +119,8 @@ export const ExternalDataDestinationsPartialUpdateBody = /* @__PURE__ */ zod.objexport const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMin = 0export const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMax = 5184000+export const externalDataSchemasUpdateBodyFullRefreshIntervalDaysMax = 90+export const externalDataSchemasUpdateBodyApiVersionMax = 128export const ExternalDataSchemasUpdateBody = /* @__PURE__ */ zod@@ -173,6 +175,14 @@ export const ExternalDataSchemasUpdateBody = /* @__PURE__ */ zod'How often to sync. The fastest sync frequency is 5 minutes.\n\n\* `never` - never\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).'),+ full_refresh_interval_days: zod+ .number()+ .min(1)+ .max(externalDataSchemasUpdateBodyFullRefreshIntervalDaysMax)+ .nullish()+ .describe(+ 'Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency.'+ ),primary_key_columns: zod.array(zod.string()).nullish().describe('Column names for primary key deduplication.'),cdc_table_mode: zod.union([@@ -220,6 +230,8 @@ export const ExternalDataSchemasUpdateBody = /* @__PURE__ */ zodexport const externalDataSchemasPartialUpdateBodyIncrementalFieldLookbackSecondsMin = 0export const externalDataSchemasPartialUpdateBodyIncrementalFieldLookbackSecondsMax = 5184000+export const externalDataSchemasPartialUpdateBodyFullRefreshIntervalDaysMax = 90+export const externalDataSchemasPartialUpdateBodyApiVersionMax = 128export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod@@ -274,6 +286,14 @@ export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod'How often to sync. The fastest sync frequency is 5 minutes.\n\n\* `never` - never\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).'),+ full_refresh_interval_days: zod+ .number()+ .min(1)+ .max(externalDataSchemasPartialUpdateBodyFullRefreshIntervalDaysMax)+ .nullish()+ .describe(+ 'Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency.'+ ),primary_key_columns: zod.array(zod.string()).nullish().describe('Column names for primary key deduplication.'),cdc_table_mode: zod.union([@@ -332,107 +352,6 @@ export const ExternalDataSchemasDestinationsPartialUpdateBody = /* @__PURE__ */),})-export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMin = 0-export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMax = 5184000--export const externalDataSchemasIncrementalFieldsCreateBodyApiVersionMax = 128--export const ExternalDataSchemasIncrementalFieldsCreateBody = /* @__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(externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMin)- .max(externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMax)- .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', '5min', '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day'])- .describe(- '\* `never` - never\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. The fastest sync frequency is 5 minutes.\n\n\* `never` - never\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."- ),- api_version: zod- .string()- .max(externalDataSchemasIncrementalFieldsCreateBodyApiVersionMax)- .nullish()- .describe(- "Vendor API version override for this schema. `null` (default) syncs on the source's pinned version. Must be one of the source type's supported versions. User-managed: version-migration tooling never changes it. Not available for webhook-sync schemas."- ),- })- .describe('A schema of an external data source: its sync configuration and the warehouse table it syncs into.')-/*** Create, Read, Update and Delete External data Sources.*/@@ -457,6 +376,8 @@ export const ExternalDataSourcesPartialUpdateBody = /* @__PURE__ */ zod/*** Create, Read, Update and Delete External data Sources.*/+export const externalDataSourcesBulkUpdateSchemasPartialUpdateBodySchemasItemFullRefreshIntervalDaysMax = 90+export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({schemas: zod.array(@@ -483,6 +404,14 @@ export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = /* @__PURE_incremental_field_type: zod.string().nullish().describe('Type of the incremental cursor field.'),sync_frequency: zod.string().nullish().describe('Human-readable sync frequency value.'),sync_time_of_day: zod.iso.time({}).nullish().describe('UTC anchor time for scheduled syncs.'),+ full_refresh_interval_days: zod+ .number()+ .min(1)+ .max(externalDataSourcesBulkUpdateSchemasPartialUpdateBodySchemasItemFullRefreshIntervalDaysMax)+ .nullish()+ .describe(+ 'Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row. Re-imported rows count toward usage, and workflows and destinations that run on new rows of the table run again for every row. Incremental, append, and xmin syncs only, and never shorter than the sync frequency.'+ ),primary_key_columns: zod.array(zod.string()).nullish()diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yamlindex 909792b7bddf..7bcc33f9d9eb 100644--- a/products/warehouse_sources/mcp/tools.yaml+++ b/products/warehouse_sources/mcp/tools.yaml@@ -231,18 +231,19 @@ tools:idempotent: truetitle: Update data warehouse table schema sync configdescription: "Update one table schema's sync configuration: enable/disable syncing (should_sync), sync_type- (incremental, full_refresh, append, webhook, cdc, xmin), sync frequency and UTC time of day, incremental- field (plus type and lookback window), primary key columns, CDC table mode, column selection- (enabled_columns), row filters, and vendor API version. Changes take effect on the next sync, not- retroactively. Before changing incremental_field or sync_type, call- 'external-data-schemas-incremental-fields-create' to see which fields and sync methods the source actually- supports; before switching to cdc, validate with 'external-data-sources-check-cdc-prerequisites-create'. To- run a sync immediately after reconfiguring, use 'external-data-schemas-reload'. This is also how a table- reported by `incremental_sync_blocked` is resolved: send primary_key_columns, or a different sync_type, or- should_sync=true to retry a table fixed at the source. For `duplicate_primary_key`, a different key is- refused once data has synced, because rows already merged under the old key would repeat; delete the synced- data first with 'external-data-schemas-delete-data', or fix the duplicates at the source and retry. That- field reports the last run's failure, so it clears once a run succeeds rather than when the update lands."+ (incremental, full_refresh, append, webhook, cdc, xmin), sync frequency and UTC time of day, scheduled full+ refresh interval (full_refresh_interval_days), incremental field (plus type and lookback window), primary+ key columns, CDC table mode, column selection (enabled_columns), row filters, and vendor API version.+ Changes take effect on the next sync, not retroactively. Before changing incremental_field or sync_type,+ call 'external-data-schemas-incremental-fields-create' to see which fields and sync methods the source+ actually supports; before switching to cdc, validate with+ 'external-data-sources-check-cdc-prerequisites-create'. To run a sync immediately after reconfiguring, use+ 'external-data-schemas-reload'. This is also how a table reported by `incremental_sync_blocked` is resolved:+ send primary_key_columns, or a different sync_type, or should_sync=true to retry a table fixed at the+ source. For `duplicate_primary_key`, a different key is refused once data has synced, because rows already+ merged under the old key would repeat; delete the synced data first with+ 'external-data-schemas-delete-data', or fix the duplicates at the source and retry. That field reports the+ last run's failure, so it clears once a run succeeds rather than when the update lands."external-data-schemas-reload:operation: external_data_schemas_reload_createenabled: true@@ -269,7 +270,9 @@ tools:description: >Trigger a full resync for a table schema, discarding all previously synced data and re-importing from thesource. This cancels any running sync first, then resets the pipeline state. Use this when data is corrupt- or out of sync.+ or out of sync. To re-import on a recurring schedule, for example to remove rows deleted at the source from+ an incremental table, set full_refresh_interval_days with 'external-data-schemas-partial-update' instead of+ calling this repeatedly.external-data-schemas-retrieve:operation: external_data_schemas_retrieveenabled: true@@ -300,12 +303,13 @@ tools:title: Update many table schemas in one requestdescription: >Apply sync configuration to several of a source's table schemas at once: enable or disable syncing- (should_sync), sync_type, sync frequency and UTC time of day, incremental field, and primary key columns.- Each entry needs the schema id plus the fields to change. Prefer this over looping- 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source,- such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before- anything is written, and a schema that fails is reported by name while the rest of the batch is saved.- Changes take effect on the next sync, not retroactively.+ (should_sync), sync_type, sync frequency and UTC time of day, scheduled full refresh interval+ (full_refresh_interval_days), incremental field, and primary key columns. Each entry needs the schema id+ plus the fields to change. Prefer this over looping 'external-data-schemas-partial-update' when+ reconfiguring more than a couple of tables of the same source, such as moving every table that cannot sync+ incrementally onto full_refresh. Every entry is validated before anything is written, and a schema that+ fails is reported by name while the rest of the batch is saved. Changes take effect on the next sync, not+ retroactively.external-data-sources-cdc-status-retrieve:operation: external_data_sources_cdc_status_retrieveenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 722e08422d69..37202c8f5c60 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5187,7 +5187,7 @@}},"external-data-schemas-partial-update": {- "description": "Update one table schema's sync configuration: enable/disable syncing (should_sync), sync_type (incremental, full_refresh, append, webhook, cdc, xmin), sync frequency and UTC time of day, incremental field (plus type and lookback window), primary key columns, CDC table mode, column selection (enabled_columns), row filters, and vendor API version. Changes take effect on the next sync, not retroactively. Before changing incremental_field or sync_type, call 'external-data-schemas-incremental-fields-create' to see which fields and sync methods the source actually supports; before switching to cdc, validate with 'external-data-sources-check-cdc-prerequisites-create'. To run a sync immediately after reconfiguring, use 'external-data-schemas-reload'. This is also how a table reported by `incremental_sync_blocked` is resolved: send primary_key_columns, or a different sync_type, or should_sync=true to retry a table fixed at the source. For `duplicate_primary_key`, a different key is refused once data has synced, because rows already merged under the old key would repeat; delete the synced data first with 'external-data-schemas-delete-data', or fix the duplicates at the source and retry. That field reports the last run's failure, so it clears once a run succeeds rather than when the update lands.",+ "description": "Update one table schema's sync configuration: enable/disable syncing (should_sync), sync_type (incremental, full_refresh, append, webhook, cdc, xmin), sync frequency and UTC time of day, scheduled full refresh interval (full_refresh_interval_days), incremental field (plus type and lookback window), primary key columns, CDC table mode, column selection (enabled_columns), row filters, and vendor API version. Changes take effect on the next sync, not retroactively. Before changing incremental_field or sync_type, call 'external-data-schemas-incremental-fields-create' to see which fields and sync methods the source actually supports; before switching to cdc, validate with 'external-data-sources-check-cdc-prerequisites-create'. To run a sync immediately after reconfiguring, use 'external-data-schemas-reload'. This is also how a table reported by `incremental_sync_blocked` is resolved: send primary_key_columns, or a different sync_type, or should_sync=true to retry a table fixed at the source. For `duplicate_primary_key`, a different key is refused once data has synced, because rows already merged under the old key would repeat; delete the synced data first with 'external-data-schemas-delete-data', or fix the duplicates at the source and retry. That field reports the last run's failure, so it clears once a run succeeds rather than when the update lands.","category": "Warehouse sources","feature": "warehouse_sources","summary": "Update data warehouse table schema sync config",@@ -5215,7 +5215,7 @@}},"external-data-schemas-resync": {- "description": "Trigger a full resync for a table schema, discarding all previously synced data and re-importing from the source. This cancels any running sync first, then resets the pipeline state. Use this when data is corrupt or out of sync.",+ "description": "Trigger a full resync for a table schema, discarding all previously synced data and re-importing from the source. This cancels any running sync first, then resets the pipeline state. Use this when data is corrupt or out of sync. To re-import on a recurring schedule, for example to remove rows deleted at the source from an incremental table, set full_refresh_interval_days with 'external-data-schemas-partial-update' instead of calling this repeatedly.","category": "Warehouse sources","feature": "warehouse_sources","summary": "Resync table schema from scratch",@@ -5243,7 +5243,7 @@}},"external-data-sources-bulk-update-schemas": {- "description": "Apply sync configuration to several of a source's table schemas at once: enable or disable syncing (should_sync), sync_type, sync frequency and UTC time of day, incremental field, and primary key columns. Each entry needs the schema id plus the fields to change. Prefer this over looping 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source, such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before anything is written, and a schema that fails is reported by name while the rest of the batch is saved. Changes take effect on the next sync, not retroactively.",+ "description": "Apply sync configuration to several of a source's table schemas at once: enable or disable syncing (should_sync), sync_type, sync frequency and UTC time of day, scheduled full refresh interval (full_refresh_interval_days), incremental field, and primary key columns. Each entry needs the schema id plus the fields to change. Prefer this over looping 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source, such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before anything is written, and a schema that fails is reported by name while the rest of the batch is saved. Changes take effect on the next sync, not retroactively.","category": "Warehouse sources","feature": "warehouse_sources","summary": "Update many table schemas in one request",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 6102c2c3f274..cc7f810cc0ac 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5286,7 +5286,7 @@}},"external-data-schemas-partial-update": {- "description": "Update one table schema's sync configuration: enable/disable syncing (should_sync), sync_type (incremental, full_refresh, append, webhook, cdc, xmin), sync frequency and UTC time of day, incremental field (plus type and lookback window), primary key columns, CDC table mode, column selection (enabled_columns), row filters, and vendor API version. Changes take effect on the next sync, not retroactively. Before changing incremental_field or sync_type, call 'external-data-schemas-incremental-fields-create' to see which fields and sync methods the source actually supports; before switching to cdc, validate with 'external-data-sources-check-cdc-prerequisites-create'. To run a sync immediately after reconfiguring, use 'external-data-schemas-reload'. This is also how a table reported by `incremental_sync_blocked` is resolved: send primary_key_columns, or a different sync_type, or should_sync=true to retry a table fixed at the source. For `duplicate_primary_key`, a different key is refused once data has synced, because rows already merged under the old key would repeat; delete the synced data first with 'external-data-schemas-delete-data', or fix the duplicates at the source and retry. That field reports the last run's failure, so it clears once a run succeeds rather than when the update lands.",+ "description": "Update one table schema's sync configuration: enable/disable syncing (should_sync), sync_type (incremental, full_refresh, append, webhook, cdc, xmin), sync frequency and UTC time of day, scheduled full refresh interval (full_refresh_interval_days), incremental field (plus type and lookback window), primary key columns, CDC table mode, column selection (enabled_columns), row filters, and vendor API version. Changes take effect on the next sync, not retroactively. Before changing incremental_field or sync_type, call 'external-data-schemas-incremental-fields-create' to see which fields and sync methods the source actually supports; before switching to cdc, validate with 'external-data-sources-check-cdc-prerequisites-create'. To run a sync immediately after reconfiguring, use 'external-data-schemas-reload'. This is also how a table reported by `incremental_sync_blocked` is resolved: send primary_key_columns, or a different sync_type, or should_sync=true to retry a table fixed at the source. For `duplicate_primary_key`, a different key is refused once data has synced, because rows already merged under the old key would repeat; delete the synced data first with 'external-data-schemas-delete-data', or fix the duplicates at the source and retry. That field reports the last run's failure, so it clears once a run succeeds rather than when the update lands.","category": "Warehouse sources","feature": "warehouse_sources","summary": "Update data warehouse table schema sync config",@@ -5314,7 +5314,7 @@}},"external-data-schemas-resync": {- "description": "Trigger a full resync for a table schema, discarding all previously synced data and re-importing from the source. This cancels any running sync first, then resets the pipeline state. Use this when data is corrupt or out of sync.",+ "description": "Trigger a full resync for a table schema, discarding all previously synced data and re-importing from the source. This cancels any running sync first, then resets the pipeline state. Use this when data is corrupt or out of sync. To re-import on a recurring schedule, for example to remove rows deleted at the source from an incremental table, set full_refresh_interval_days with 'external-data-schemas-partial-update' instead of calling this repeatedly.","category": "Warehouse sources","feature": "warehouse_sources","summary": "Resync table schema from scratch",@@ -5342,7 +5342,7 @@}},"external-data-sources-bulk-update-schemas": {- "description": "Apply sync configuration to several of a source's table schemas at once: enable or disable syncing (should_sync), sync_type, sync frequency and UTC time of day, incremental field, and primary key columns. Each entry needs the schema id plus the fields to change. Prefer this over looping 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source, such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before anything is written, and a schema that fails is reported by name while the rest of the batch is saved. Changes take effect on the next sync, not retroactively.",+ "description": "Apply sync configuration to several of a source's table schemas at once: enable or disable syncing (should_sync), sync_type, sync frequency and UTC time of day, scheduled full refresh interval (full_refresh_interval_days), incremental field, and primary key columns. Each entry needs the schema id plus the fields to change. Prefer this over looping 'external-data-schemas-partial-update' when reconfiguring more than a couple of tables of the same source, such as moving every table that cannot sync incrementally onto full_refresh. Every entry is validated before anything is written, and a schema that fails is reported by name while the rest of the batch is saved. Changes take effect on the next sync, not retroactively.","category": "Warehouse sources","feature": "warehouse_sources","summary": "Update many table schemas in one request",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d46a99d62e13..228348a0fa1c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -43100,6 +43100,18 @@ export namespace Schemas {* @nullable*/sync_time_of_day?: string | null;+ /**+ * Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency.+ * @minimum 1+ * @maximum 90+ * @nullable+ */+ full_refresh_interval_days?: number | null;+ /**+ * When the next scheduled full refresh is due. The first scheduled sync that starts at most an hour before this time re-imports the table. Saving a new interval, or any full resync, moves it one interval ahead.+ * @nullable+ */+ readonly next_full_refresh_at: string | null;/** @nullable */readonly description: string | null;/**@@ -43206,6 +43218,13 @@ export namespace Schemas {* @nullable*/sync_time_of_day?: string | null;+ /**+ * Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row. Re-imported rows count toward usage, and workflows and destinations that run on new rows of the table run again for every row. Incremental, append, and xmin syncs only, and never shorter than the sync frequency.+ * @minimum 1+ * @maximum 90+ * @nullable+ */+ full_refresh_interval_days?: number | null;/*** Column names for primary key deduplication.* @nullable@@ -73230,6 +73249,18 @@ export namespace Schemas {* @nullable*/sync_time_of_day?: string | null;+ /**+ * Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency.+ * @minimum 1+ * @maximum 90+ * @nullable+ */+ full_refresh_interval_days?: number | null;+ /**+ * When the next scheduled full refresh is due. The first scheduled sync that starts at most an hour before this time re-imports the table. Saving a new interval, or any full resync, moves it one interval ahead.+ * @nullable+ */+ readonly next_full_refresh_at?: string | null;/** @nullable */readonly description?: string | null;/**diff --git a/services/mcp/src/generated/warehouse_sources/api.ts b/services/mcp/src/generated/warehouse_sources/api.tsindex 7425ce38dfb1..0ca45836d852 100644--- a/services/mcp/src/generated/warehouse_sources/api.ts+++ b/services/mcp/src/generated/warehouse_sources/api.ts@@ -77,6 +77,8 @@ export const ExternalDataSchemasPartialUpdateParams = () => zod.object({export const externalDataSchemasPartialUpdateBodyIncrementalFieldLookbackSecondsMin = 0export const externalDataSchemasPartialUpdateBodyIncrementalFieldLookbackSecondsMax = 5184000+export const externalDataSchemasPartialUpdateBodyFullRefreshIntervalDaysMax = 90+export const externalDataSchemasPartialUpdateBodyApiVersionMax = 128export const ExternalDataSchemasPartialUpdateBody = () => zod@@ -131,6 +133,14 @@ export const ExternalDataSchemasPartialUpdateBody = () => zod'How often to sync. The fastest sync frequency is 5 minutes.\n\n\* `never` - never\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).'),+ full_refresh_interval_days: zod+ .number()+ .min(1)+ .max(externalDataSchemasPartialUpdateBodyFullRefreshIntervalDaysMax)+ .nullish()+ .describe(+ 'Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency.'+ ),primary_key_columns: zod.array(zod.string()).nullish().describe('Column names for primary key deduplication.'),cdc_table_mode: zod.union([@@ -216,107 +226,6 @@ export const ExternalDataSchemasIncrementalFieldsCreateParams = () => zod.object),})-export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMin = 0-export const externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMax = 5184000--export const externalDataSchemasIncrementalFieldsCreateBodyApiVersionMax = 128--export const ExternalDataSchemasIncrementalFieldsCreateBody = () => 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(externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMin)- .max(externalDataSchemasIncrementalFieldsCreateBodyIncrementalFieldLookbackSecondsMax)- .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', '5min', '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day'])- .describe(- '\* `never` - never\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. The fastest sync frequency is 5 minutes.\n\n\* `never` - never\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."- ),- api_version: zod- .string()- .max(externalDataSchemasIncrementalFieldsCreateBodyApiVersionMax)- .nullish()- .describe(- "Vendor API version override for this schema. `null` (default) syncs on the source's pinned version. Must be one of the source type's supported versions. User-managed: version-migration tooling never changes it. Not available for webhook-sync schemas."- ),- })- .describe('A schema of an external data source: its sync configuration and the warehouse table it syncs into.')-/*** Trigger a sync for the schema using its configured sync method. Most methods keep the existing warehouse table and add or merge new rows, but a full-refresh schema rebuilds the whole table on every run. To force a rebuild from the source, use resync.*/@@ -1875,6 +1784,8 @@ export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams = () => zod),})+export const externalDataSourcesBulkUpdateSchemasPartialUpdateBodySchemasItemFullRefreshIntervalDaysMax = 90+export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = () => zod.object({schemas: zod.array(@@ -1901,6 +1812,14 @@ export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = () => zod.oincremental_field_type: zod.string().nullish().describe('Type of the incremental cursor field.'),sync_frequency: zod.string().nullish().describe('Human-readable sync frequency value.'),sync_time_of_day: zod.iso.time({}).nullish().describe('UTC anchor time for scheduled syncs.'),+ full_refresh_interval_days: zod+ .number()+ .min(1)+ .max(externalDataSourcesBulkUpdateSchemasPartialUpdateBodySchemasItemFullRefreshIntervalDaysMax)+ .nullish()+ .describe(+ 'Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row. Re-imported rows count toward usage, and workflows and destinations that run on new rows of the table run again for every row. Incremental, append, and xmin syncs only, and never shorter than the sync frequency.'+ ),primary_key_columns: zod.array(zod.string()).nullish()diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.tsindex 08d2c015eca2..0fa909d07bf5 100644--- a/services/mcp/src/tools/generated/warehouse_sources.ts+++ b/services/mcp/src/tools/generated/warehouse_sources.ts@@ -206,12 +206,9 @@ const externalDataSchemasDestinationsRetrieve = (): ToolBase<})const ExternalDataSchemasIncrementalFieldsCreateSchema = () => {- const ExternalDataSchemasIncrementalFieldsCreateBody = orvalSchemas.ExternalDataSchemasIncrementalFieldsCreateBody()const ExternalDataSchemasIncrementalFieldsCreateParams =orvalSchemas.ExternalDataSchemasIncrementalFieldsCreateParams()- return ExternalDataSchemasIncrementalFieldsCreateParams.omit({ project_id: true }).extend(- ExternalDataSchemasIncrementalFieldsCreateBody.shape- )+ return ExternalDataSchemasIncrementalFieldsCreateParams.omit({ project_id: true })}const externalDataSchemasIncrementalFieldsCreate = (): ToolBase<@@ -225,47 +222,9 @@ const externalDataSchemasIncrementalFieldsCreate = (): ToolBase<params: z.infer<ReturnType<typeof ExternalDataSchemasIncrementalFieldsCreateSchema>>) => {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- }- if (params.api_version !== undefined) {- body['api_version'] = params.api_version- }const result = await context.api.request<unknown>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/incremental_fields/`,- body,})return result},@@ -341,6 +300,9 @@ const externalDataSchemasPartialUpdate = (): ToolBase<if (params.sync_time_of_day !== undefined) {body['sync_time_of_day'] = params.sync_time_of_day}+ if (params.full_refresh_interval_days !== undefined) {+ body['full_refresh_interval_days'] = params.full_refresh_interval_days+ }if (params.primary_key_columns !== undefined) {body['primary_key_columns'] = params.primary_key_columns}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.jsonindex 3614025849dd..567fb6f27984 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-incremental-fields-create.json@@ -1,167 +1,9 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {- "api_version": {- "anyOf": [- {- "maxLength": 128,- "type": "string"- },- {- "type": "null"- }- ],- "description": "Vendor API version override for this schema. `null` (default) syncs on the source's pinned version. Must be one of the source type's supported versions. User-managed: version-migration tooling never changes it. Not available for webhook-sync schemas."- },- "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* `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", "5min", "15min", "30min", "1hour", "6hour", "12hour", "24hour", "7day", "30day"],- "type": "string"- },- {- "type": "null"- }- ],- "description": "How often to sync. The fastest sync frequency is 5 minutes.\n\n* `never` - never\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"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.jsonindex 3614025849dd..e545c3fb1685 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-schemas-partial-update.json@@ -40,6 +40,19 @@],"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."},+ "full_refresh_interval_days": {+ "anyOf": [+ {+ "maximum": 90,+ "minimum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row, so rows deleted at the source are removed. It runs on the first scheduled sync once the interval has passed, counted from when it was saved or from the last full resync, and can start up to an hour early. Queries keep returning the current rows until a full refresh finishes, and workflows and destinations that run on new rows of the table run again for every row. Available for incremental, append, and xmin syncs only, and never shorter than the sync frequency."+ },"id": {"description": "A UUID string identifying this external data schema.","type": "string"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-bulk-update-schemas.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-bulk-update-schemas.jsonindex 154eff7d8b2f..8baff5e1c528 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-bulk-update-schemas.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-bulk-update-schemas.json@@ -40,6 +40,19 @@],"description": "Columns to sync. Null means sync all columns."},+ "full_refresh_interval_days": {+ "anyOf": [+ {+ "maximum": 90,+ "minimum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Days between scheduled full refreshes, from 1 to 90, or null for none. A full refresh wipes the table and re-imports every row. Re-imported rows count toward usage, and workflows and destinations that run on new rows of the table run again for every row. Incremental, append, and xmin syncs only, and never shorter than the sync frequency."+ },"id": {"description": "Schema identifier to update.","type": "string"