Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(warehouse-sources): return frozen dataclasses instead of tuples (#76143)

Arno Hillendb64b5ac1cab
diff --git a/products/data_warehouse/backend/sql_warehouse_migration.py b/products/data_warehouse/backend/sql_warehouse_migration.py
index 33e10c2d9d38..14e1c05caa33 100644
--- a/products/data_warehouse/backend/sql_warehouse_migration.py
+++ b/products/data_warehouse/backend/sql_warehouse_migration.py
@@ -11,6 +11,7 @@ from typing import Any
from products.warehouse_sources.backend.facade.models import ExternalDataSource
from products.warehouse_sources.backend.facade.source_management import (
+ DottedNameParts,
SourceRegistry,
SQLSource,
fill_missing_from_dotted_name,
@@ -143,8 +144,8 @@ def detect_schema_clear_transition(
return existing.strip()
-def _extract_source_location_from_row(row: Any) -> tuple[str | None, str | None]:
- """`(source_schema, source_table_name)` — metadata first, dotted name fallback, else `(None, None)`."""
+def _extract_source_location_from_row(row: Any) -> DottedNameParts:
+ """Source schema/table for a row: metadata first, dotted name fallback, else both `None`."""
metadata = (row.sync_type_config or {}).get("schema_metadata")
source_schema: str | None = None
source_table_name: str | None = None
@@ -153,7 +154,7 @@ def _extract_source_location_from_row(row: Any) -> tuple[str | None, str | None]
source_schema = metadata["source_schema"]
if isinstance(metadata.get("source_table_name"), str):
source_table_name = metadata["source_table_name"]
- return fill_missing_from_dotted_name(source_schema, source_table_name, row.name)
+ return fill_missing_from_dotted_name(schema=source_schema, table=source_table_name, display_name=row.name)
def apply_on_refresh(*, source: ExternalDataSource, team_id: int) -> dict[str, str]:
@@ -173,9 +174,9 @@ def apply_on_refresh(*, source: ExternalDataSource, team_id: int) -> dict[str, s
unqualified_rows: list[ExternalDataSchema] = []
for row in rows:
if "." in row.name:
- source_schema, source_table_name = _extract_source_location_from_row(row)
- if source_schema and source_table_name:
- qualified_rows_by_table_name.setdefault(source_table_name, []).append((source_schema, row))
+ location = _extract_source_location_from_row(row)
+ if location.schema and location.table:
+ qualified_rows_by_table_name.setdefault(location.table, []).append((location.schema, row))
else:
unqualified_rows.append(row)
@@ -183,17 +184,17 @@ def apply_on_refresh(*, source: ExternalDataSource, team_id: int) -> dict[str, s
name_substitutions: dict[str, str] = {}
for legacy in unqualified_rows:
- legacy_metadata_source_schema, legacy_metadata_source_table_name = _extract_source_location_from_row(legacy)
+ legacy_location = _extract_source_location_from_row(legacy)
qualified_matches = qualified_rows_by_table_name.get(legacy.name, [])
# Disambiguate multi-match using legacy's own pinned metadata.
- if len(qualified_matches) > 1 and legacy_metadata_source_schema is not None:
- filtered = [m for m in qualified_matches if m[0] == legacy_metadata_source_schema]
+ if len(qualified_matches) > 1 and legacy_location.schema is not None:
+ filtered = [m for m in qualified_matches if m[0] == legacy_location.schema]
if len(filtered) == 1:
qualified_matches = filtered
target_source_schema: str | None
- target_source_table_name: str | None = legacy_metadata_source_table_name
+ target_source_table_name: str | None = legacy_location.table
duplicate: Any | None = None
if len(qualified_matches) == 1:
@@ -201,8 +202,8 @@ def apply_on_refresh(*, source: ExternalDataSource, team_id: int) -> dict[str, s
elif len(qualified_matches) > 1:
# Ambiguous — let the user resolve via the UI.
continue
- elif legacy_metadata_source_schema is not None:
- target_source_schema = legacy_metadata_source_schema
+ elif legacy_location.schema is not None:
+ target_source_schema = legacy_location.schema
elif default_schema is not None:
target_source_schema = default_schema
else:
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 4cd5a19ecbc1..31bff95a1dd1 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -43,6 +43,7 @@ _LAZY = {
"validate_and_coerce_row_filters": "sources.common.sql",
"SQLSource": "sources.common.sql.base",
"extract_available_column_names": "sources.common.sql.metadata",
+ "DottedNameParts": "sources.common.sql.location",
"fill_missing_from_dotted_name": "sources.common.sql.location",
"normalize_namespace": "sources.common.sql.location",
"filter_columns_by_enabled_columns": "sources.common.sql.projection",
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 4729c67e6f9f..43182bd440ea 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -3,6 +3,7 @@ import sys
import uuid
import fnmatch
from collections.abc import Callable, Iterable
+from dataclasses import dataclass
from datetime import date, datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal, Optional
@@ -999,6 +1000,12 @@ def _update_labels(old_schemas: list["ExternalDataSchema"], new_schemas: dict[st
schema.save(update_fields=["label", "updated_at"])
+@dataclass(frozen=True, kw_only=True, slots=True)
+class SchemaSyncResult:
+ created: list[str]
+ deleted: list[str]
+
+
def sync_old_schemas_with_new_schemas(
new_schemas: dict[str, str | None],
source_id: str,
@@ -1006,7 +1013,7 @@ def sync_old_schemas_with_new_schemas(
descriptions: dict[str, str | None] | None = None,
strict_name_match: bool = False,
schema_metadata_by_name: dict[str, dict] | None = None,
-) -> tuple[list[str], list[str]]:
+) -> SchemaSyncResult:
old_schemas = get_all_schemas_for_source_id(source_id=source_id, team_id=team_id)
old_schemas_names = [schema.name for schema in old_schemas]
@@ -1099,7 +1106,7 @@ def sync_old_schemas_with_new_schemas(
s.status = ExternalDataSchema.Status.COMPLETED
s.save()
- return actually_created, deleted_schemas
+ return SchemaSyncResult(created=actually_created, deleted=deleted_schemas)
def schema_name_matches_auto_sync_patterns(name: str, patterns: list[str] | None) -> bool:
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index de704edcc84c..4d6dc90780e5 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -1700,6 +1700,13 @@ class IntegrationAccountsResponseSerializer(serializers.Serializer):
)
[email protected](frozen=True, kw_only=True, slots=True)
+class ResolvedStoredCredential:
+ payload: dict
+ credential: PendingSourceCredential | None
+ error_response: Response | None
+
+
@extend_schema(extensions={"x-product": "warehouse_sources"})
class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
"""
@@ -1882,9 +1889,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
.order_by(self.ordering)
)
- def _resolve_stored_credential(
- self, source_type: str, payload: dict
- ) -> tuple[dict, PendingSourceCredential | None, Response | None]:
+ def _resolve_stored_credential(self, source_type: str, payload: dict) -> ResolvedStoredCredential:
"""Merge a connect-link stored credential into `payload` when it carries a `credential_id`.
Lets the create and setup flows reference credentials the user entered on the connect page
@@ -1897,25 +1902,25 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"""
credential_id = payload.pop("credential_id", None)
if credential_id is None:
- return payload, None, None
+ return ResolvedStoredCredential(payload=payload, credential=None, error_response=None)
try:
credential = PendingSourceCredential.objects.for_team(self.team_id).get(
id=credential_id, created_by=cast(User, self.request.user), expires_at__gt=timezone.now()
)
except (PendingSourceCredential.DoesNotExist, ValueError, TypeError, DjangoValidationError):
- return (
- payload,
- None,
- Response(
+ return ResolvedStoredCredential(
+ payload=payload,
+ credential=None,
+ error_response=Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": f"Stored credential '{credential_id}' not found or expired"},
),
)
if credential.source_type != source_type:
- return (
- payload,
- None,
- Response(
+ return ResolvedStoredCredential(
+ payload=payload,
+ credential=None,
+ error_response=Response(
status=status.HTTP_400_BAD_REQUEST,
data={
"message": f"Stored credential '{credential_id}' is for "
@@ -1924,7 +1929,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
),
)
# Stored credentials win over inline keys so an agent can't override what the user entered.
- return {**payload, **credential.payload}, credential, None
+ return ResolvedStoredCredential(
+ payload={**payload, **credential.payload}, credential=credential, error_response=None
+ )
@extend_schema(
request=ExternalDataSourceCreateSerializer, responses={201: ExternalDataSourceCreateResponseSerializer}
@@ -1943,14 +1950,14 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# A `credential_id` in the payload references connection details the user entered on the
# connect-link page — resolve it to the real secrets so `create` can target a specific
# `schemas` set (unlike `setup`, which discovers and enables every table).
- payload, credential, credential_error = self._resolve_stored_credential(source_type, payload)
- if credential_error is not None:
- return credential_error
+ resolved = self._resolve_stored_credential(source_type, payload)
+ if resolved.error_response is not None:
+ return resolved.error_response
response = self._create_external_data_source(
request,
source_type=source_type,
- payload=payload,
+ payload=resolved.payload,
prefix=serializer.validated_data.get("prefix"),
description=serializer.validated_data.get("description"),
access_method=serializer.validated_data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE),
@@ -1958,8 +1965,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
direct_query_enabled=serializer.validated_data.get("direct_query_enabled", False),
)
# Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.
- if credential is not None and response.status_code == status.HTTP_201_CREATED:
- credential.delete()
+ if resolved.credential is not None and response.status_code == status.HTTP_201_CREATED:
+ resolved.credential.delete()
return response
@extend_schema(
@@ -3001,7 +3008,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# qualified rows for the others, so bare↔qualified tail matching would wrongly collapse
# them; match names exactly and seed per-resource location metadata on new rows.
namespaced_adapter = get_namespaced_resource_adapter(instance.source_type)
- schemas_created, schemas_deleted = sync_old_schemas_with_new_schemas(
+ sync_result = sync_old_schemas_with_new_schemas(
schema_names,
source_id=str(instance.id),
team_id=self.team_id,
@@ -3011,6 +3018,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if namespaced_adapter is not None
else None,
)
+ # Mutable local: engine reconciliation below may extend the deleted set.
+ schemas_deleted = sync_result.deleted
if engine is not None:
reconciled_deleted_schemas = engine.reconcile_schemas(
@@ -3024,18 +3033,18 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
source.reconcile_schema_metadata(source=instance, source_schemas=schemas, team_id=self.team_id)
# Outside the atomic block: schedule creation talks to Temporal, which must not run under
- # the source row lock or against rows that could still roll back. `schemas_created` holds
+ # the source row lock or against rows that could still roll back. `sync_result.created` holds
# post-substitution stored names, so remap the discovered names to match.
auto_enabled_names: list[str] = []
- if schemas_created:
+ if sync_result.created:
source_schemas_by_name = {name_substitutions.get(s.name, s.name): s for s in schemas}
- auto_enabled_names = auto_enable_new_schemas(instance, schemas_created, source_schemas_by_name)
+ auto_enabled_names = auto_enable_new_schemas(instance, sync_result.created, source_schemas_by_name)
logger.debug(
"refresh_schemas completed",
source_id=str(instance.id),
team_id=self.team_id,
- added=len(schemas_created),
+ added=len(sync_result.created),
deleted=len(schemas_deleted),
auto_enabled=len(auto_enabled_names),
total_tables_seen=len(schemas),
@@ -3043,7 +3052,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
return Response(
status=status.HTTP_200_OK,
data={
- "added": len(schemas_created),
+ "added": len(sync_result.created),
"deleted": len(schemas_deleted),
"auto_enabled": len(auto_enabled_names),
"total_tables_seen": len(schemas),
@@ -3191,9 +3200,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if secret_ref_response is not None:
return secret_ref_response
- payload, credential, credential_error = self._resolve_stored_credential(source_type, payload)
- if credential_error is not None:
- return credential_error
+ resolved = self._resolve_stored_credential(source_type, payload)
+ if resolved.error_response is not None:
+ return resolved.error_response
+ # Mutable local: the CustomSource branch below rewrites payload keys before source creation.
+ payload = resolved.payload
source_type_model = ExternalDataSourceType(source_type)
source = SourceRegistry.get_source(source_type_model)
@@ -3250,8 +3261,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
skip_credential_validation=True,
)
# Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.
- if credential is not None and response.status_code == status.HTTP_201_CREATED:
- credential.delete()
+ if resolved.credential is not None and response.status_code == status.HTTP_201_CREATED:
+ resolved.credential.delete()
if response.status_code == status.HTTP_201_CREATED and isinstance(source, WebhookSource):
webhook_result = self._auto_register_webhook(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index fafcca9d5adc..bca700463f6d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -561,8 +561,7 @@ class CDCExtractActivity:
land in a parallel Delta table no query reads. `name` and folder diverge
for rows renamed bare→qualified (`name="public.users"`, folder `users`).
"""
- _table_storage_name, folder_name = resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name)
- return folder_name
+ return resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name).folder_name
def _partition_kwargs(self, schema: ExternalDataSchema) -> dict[str, typing.Any]:
"""Replay snapshot partitioning so CDC rows match the target Delta.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 1795ab2a179b..673bac0bfc60 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -1,4 +1,5 @@
from contextlib import asynccontextmanager
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, NoReturn
from django.conf import settings
@@ -547,6 +548,12 @@ def cleanup_memory(pa_memory_pool: pa.MemoryPool, py_table: pa.Table | None = No
pa_memory_pool.release_unused()
+@dataclass(frozen=True, kw_only=True, slots=True)
+class IncrementalFieldValues:
+ last_value: Any
+ earliest_value: Any
+
+
async def update_incremental_field_values(
schema: "ExternalDataSchema",
pa_table: pa.Table,
@@ -556,7 +563,7 @@ async def update_incremental_field_values(
logger: FilteringBoundLogger,
log_prefix: str = "",
staging_run_uuid: str | None = None,
-) -> tuple[Any, Any]:
+) -> IncrementalFieldValues:
last_value = get_incremental_field_value(schema, pa_table)
if last_value is not None:
@@ -589,7 +596,9 @@ async def update_incremental_field_values(
earliest_value, type="earliest"
)
- return last_incremental_field_value, earliest_incremental_field_value
+ return IncrementalFieldValues(
+ last_value=last_incremental_field_value, earliest_value=earliest_incremental_field_value
+ )
async def update_row_tracking_after_batch(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py
index e17c04ff16d7..7bfb07f48d8f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from dataclasses import dataclass
from datetime import date, datetime
from typing import TYPE_CHECKING
from zoneinfo import ZoneInfo
@@ -74,8 +75,14 @@ def build_table_name(source: ExternalDataSource, schema_name: str):
return f"{source.prefix or ''}{source.source_type}_{safe_schema_name}".lower()
-def resolve_table_and_folder_names(schema_name: str, resolved_s3_folder_name: str | None) -> tuple[str, str]:
- """Return `(table_storage_name, folder_name)` for a schema row.
+@dataclass(frozen=True, kw_only=True, slots=True)
+class ResolvedSchemaNames:
+ table_storage_name: str
+ folder_name: str
+
+
+def resolve_table_and_folder_names(schema_name: str, resolved_s3_folder_name: str | None) -> ResolvedSchemaNames:
+ """Return the `table_storage_name` and `folder_name` for a schema row.
These are intentionally different normalizations:
- The S3 folder is the *snake_cased* identifier (`BalanceTransaction` -> `balance_transaction`).
@@ -92,7 +99,7 @@ def resolve_table_and_folder_names(schema_name: str, resolved_s3_folder_name: st
folder_name = NamingConvention.normalize_identifier(resolved_s3_folder_name or schema_name)
is_folder_pinned = folder_name != NamingConvention.normalize_identifier(schema_name)
table_storage_name = folder_name if is_folder_pinned else schema_name
- return table_storage_name, folder_name
+ return ResolvedSchemaNames(table_storage_name=table_storage_name, folder_name=folder_name)
def sync_revenue_analytics_views(schema: ExternalDataSchema, source: ExternalDataSource) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
index 6085c979d702..e6b49e5575b3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
@@ -180,11 +180,9 @@ async def validate_schema_and_update_table(
# The HogQL table name derives from the raw schema name (only lower-cased); the S3 folder is
# the snake_cased `s3_folder_name`. They differ on purpose — see `resolve_table_and_folder_names`.
- table_storage_name, normalized_schema_name = resolve_table_and_folder_names(
- _schema_name, external_data_schema.resolved_s3_folder_name
- )
- table_name = build_table_name(job.pipeline, table_storage_name)
- new_url_pattern = job.url_pattern_by_schema(normalized_schema_name)
+ names = resolve_table_and_folder_names(_schema_name, external_data_schema.resolved_s3_folder_name)
+ table_name = build_table_name(job.pipeline, names.table_storage_name)
+ new_url_pattern = job.url_pattern_by_schema(names.folder_name)
try:
logger.info(f"Row count for {_schema_name} ({_schema_id}) is {row_count}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
index 8687ab4bba5d..7e00696ae7db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
@@ -1,6 +1,6 @@
import sys
import time
-from typing import Any, Generic, Literal
+from typing import TYPE_CHECKING, Any, Generic, Literal
import pyarrow as pa
import deltalake as deltalake
@@ -68,6 +68,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
)
from products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
+ ImportJobModels,
+ )
+
class PipelineNonDLT(Generic[ResumableData]):
_resource: SourceResponse
@@ -93,11 +98,9 @@ class PipelineNonDLT(Generic[ResumableData]):
job_id: str,
reset_pipeline: bool,
shutdown_monitor: ShutdownMonitor,
- job: ExternalDataJob,
- schema: ExternalDataSchema,
- source: ExternalDataSource,
- table: DataWarehouseTable | None,
resumable_source_manager: ResumableSourceManager[ResumableData] | None,
+ *,
+ models: "ImportJobModels",
) -> None:
self._resource = source_response
self._resource_name = source_response.name
@@ -105,19 +108,19 @@ class PipelineNonDLT(Generic[ResumableData]):
# Persisted PK (user override or earlier detection) > live-detected > `id` fallback. Keeps
# the merge key stable across runs when live detection (e.g. Snowflake SHOW PRIMARY KEYS)
# intermittently returns nothing.
- self._resource.primary_keys = resolve_primary_keys(schema, self._resource)
+ self._resource.primary_keys = resolve_primary_keys(models.schema, self._resource)
- self._job = job
+ self._job = models.job
self._reset_pipeline = reset_pipeline
self._logger = logger
self._load_id = time.time_ns()
- self._schema = schema
- self._source = source
- self._table = table
+ self._schema = models.schema
+ self._source = models.source
+ self._table = models.table
# xmin reads deltas and upserts on the primary key, so it writes incrementally too — never
# as a full_refresh overwrite, which would wipe earlier data on the second (delta-only) sync.
- self._is_incremental = schema.is_incremental or schema.is_webhook or schema.is_xmin
+ self._is_incremental = models.schema.is_incremental or models.schema.is_webhook or models.schema.is_xmin
self._delta_table_ref = DeltaTableRef(self._resource_name, self._job, self._logger)
self._resumable_source_manager = resumable_source_manager
@@ -142,12 +145,12 @@ class PipelineNonDLT(Generic[ResumableData]):
self._shutdown_monitor = shutdown_monitor
self._last_incremental_field_value: Any = None
self._earliest_incremental_field_value: Any = process_incremental_value(
- schema.incremental_field_earliest_value, schema.incremental_field_type
+ models.schema.incremental_field_earliest_value, models.schema.incremental_field_type
)
# SQL sources project enabled_columns in their SELECT and own schema_metadata via
# introspection; managed-schema sources don't allow selection. Everything else gets the
# Delta-write-side drop plus observed-columns capture so the column picker has a catalog.
- self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(source.source_type)
+ self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(models.source.source_type)
self._observed_columns: dict[str, dict[str, Any]] = {}
async def run(self) -> PipelineResult:
@@ -347,10 +350,7 @@ class PipelineNonDLT(Generic[ResumableData]):
await self._sinks.stage_chunk(index, pa_table)
- (
- self._last_incremental_field_value,
- self._earliest_incremental_field_value,
- ) = await update_incremental_field_values(
+ incremental_values = await update_incremental_field_values(
self._schema,
pa_table,
self._resource,
@@ -358,6 +358,8 @@ class PipelineNonDLT(Generic[ResumableData]):
self._earliest_incremental_field_value,
self._logger,
)
+ self._last_incremental_field_value = incremental_values.last_value
+ self._earliest_incremental_field_value = incremental_values.earliest_value
await update_row_tracking_after_batch(
self._job.id, self._job.team_id, self._schema.id, pa_table.num_rows, self._logger
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
index c53318e1eafe..73016247e9c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
@@ -214,18 +214,18 @@ class DuckgresBatchConsumerAdapter:
if superseded:
logger.info("duckgres_superseded_obsolete_batches", count=superseded)
- backlog, oldest_age, blocked, blocked_age, failing_blocked = await DuckgresBatchQueue.get_backlog_stats(
+ stats = await DuckgresBatchQueue.get_backlog_stats(
conn,
team_ids=team_ids,
blocked_schema_ids=self._blocked_schema_ids,
eligible_schema_ids=self._eligible_schema_ids,
failing_schema_ids=self._failing_schema_ids,
)
- SINK_ELIGIBLE_BACKLOG.set(backlog)
- SINK_OLDEST_ELIGIBLE_AGE_SECONDS.set(oldest_age or 0.0)
- SINK_BLOCKED_BACKLOG.set(blocked)
- SINK_BLOCKED_OLDEST_AGE_SECONDS.set(blocked_age or 0.0)
- SINK_FAILING_BLOCKED_BACKLOG.set(failing_blocked)
+ SINK_ELIGIBLE_BACKLOG.set(stats.eligible_count)
+ SINK_OLDEST_ELIGIBLE_AGE_SECONDS.set(stats.eligible_oldest_age_seconds or 0.0)
+ SINK_BLOCKED_BACKLOG.set(stats.blocked_count)
+ SINK_BLOCKED_OLDEST_AGE_SECONDS.set(stats.blocked_oldest_age_seconds or 0.0)
+ SINK_FAILING_BLOCKED_BACKLOG.set(stats.failing_blocked_count)
orgs_at_budget = await DuckgresBatchQueue.count_orgs_at_budget(
conn, team_org_budgets=self._team_org_budgets
)
@@ -273,9 +273,9 @@ class DuckgresBatchConsumerAdapter:
logger.info(
"duckgres_maintenance_ran",
team_count=None if team_ids is None else len(team_ids),
- eligible_backlog=backlog,
- blocked_backlog=blocked,
- failing_blocked_backlog=failing_blocked,
+ eligible_backlog=stats.eligible_count,
+ blocked_backlog=stats.blocked_count,
+ failing_blocked_backlog=stats.failing_blocked_count,
orgs_at_budget=orgs_at_budget,
blocked_schema_count=None if self._blocked_schema_ids is None else len(self._blocked_schema_ids),
failing_schema_count=None if self._failing_schema_ids is None else len(self._failing_schema_ids),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
index 9d666e55ff81..a3d3b40c808b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
+from dataclasses import dataclass
from typing import Any
import psycopg
@@ -245,6 +246,15 @@ def _eligibility_ctes(scoped: bool) -> str:
),"""
+@dataclass(frozen=True, kw_only=True, slots=True)
+class BacklogStats:
+ eligible_count: int
+ eligible_oldest_age_seconds: float | None
+ blocked_count: int
+ blocked_oldest_age_seconds: float | None
+ failing_blocked_count: int
+
+
class DuckgresBatchQueue:
@staticmethod
async def get_delta_succeeded_and_lock(
@@ -688,8 +698,8 @@ class DuckgresBatchQueue:
blocked_schema_ids: list[str] | None = None,
eligible_schema_ids: list[str] | None = None,
failing_schema_ids: list[str] | None = None,
- ) -> tuple[int, float | None, int, float | None, int]:
- """(eligible_count, eligible_oldest_age, blocked_count, blocked_oldest_age, failing_blocked_count).
+ ) -> BacklogStats:
+ """Backlog counts and ages split into eligible, blocked, and failing-blocked buckets.
Eligible = delta-succeeded, unapplied, non-failed data batches the sink
can claim now — the lag/alert signal (7-day retention and permanent run
@@ -750,8 +760,20 @@ class DuckgresBatchQueue:
return float(v) if v is not None else None
if row is None:
- return 0, None, 0, None, 0
- return int(row[0]), _age(row[1]), int(row[2]), _age(row[3]), int(row[4])
+ return BacklogStats(
+ eligible_count=0,
+ eligible_oldest_age_seconds=None,
+ blocked_count=0,
+ blocked_oldest_age_seconds=None,
+ failing_blocked_count=0,
+ )
+ return BacklogStats(
+ eligible_count=int(row[0]),
+ eligible_oldest_age_seconds=_age(row[1]),
+ blocked_count=int(row[2]),
+ blocked_oldest_age_seconds=_age(row[3]),
+ failing_blocked_count=int(row[4]),
+ )
@staticmethod
async def update_status(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
index 1d666f9edc4f..5683994b60a4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (
duckgres_sink_enablement,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import BacklogStats
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
PendingBatch,
)
@@ -322,7 +323,13 @@ class TestDuckgresEnablementGating:
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",
new_callable=AsyncMock,
- return_value=(0, None, 0, None, 0),
+ return_value=BacklogStats(
+ eligible_count=0,
+ eligible_oldest_age_seconds=None,
+ blocked_count=0,
+ blocked_oldest_age_seconds=None,
+ failing_blocked_count=0,
+ ),
) as mock_backlog,
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",
@@ -381,7 +388,13 @@ class TestDuckgresEnablementGating:
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",
new_callable=AsyncMock,
- return_value=(0, None, 0, None, 0),
+ return_value=BacklogStats(
+ eligible_count=0,
+ eligible_oldest_age_seconds=None,
+ blocked_count=0,
+ blocked_oldest_age_seconds=None,
+ failing_blocked_count=0,
+ ),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",
@@ -423,7 +436,13 @@ class TestDuckgresEnablementGating:
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",
new_callable=AsyncMock,
- return_value=(0, None, 0, None, 0),
+ return_value=BacklogStats(
+ eligible_count=0,
+ eligible_oldest_age_seconds=None,
+ blocked_count=0,
+ blocked_oldest_age_seconds=None,
+ failing_blocked_count=0,
+ ),
),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
index c45925fe4fa8..3a8eeee95b23 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
@@ -475,45 +475,39 @@ class TestDuckgresTeamFilterAndBacklog:
batch_id = await _insert_batch(conn, sync_type="incremental")
await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)
- count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(conn)
- assert (count, blocked, failing) == (1, 0, 0)
- assert oldest_age is not None and oldest_age >= 0
- assert blocked_age is None
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn)
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (1, 0, 0)
+ assert stats.eligible_oldest_age_seconds is not None and stats.eligible_oldest_age_seconds >= 0
+ assert stats.blocked_oldest_age_seconds is None
# The same batch counts as blocked (not eligible) once its schema is gated.
- count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(
- conn, blocked_schema_ids=["schema-1"]
- )
- assert (count, blocked, failing) == (0, 1, 0)
- assert oldest_age is None and blocked_age is not None
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn, blocked_schema_ids=["schema-1"])
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (0, 1, 0)
+ assert stats.eligible_oldest_age_seconds is None and stats.blocked_oldest_age_seconds is not None
# A hard-blocked schema's batches leave the pageable blocked bucket
# (count AND oldest-age) for the failing one — a wedged schema must not
# be able to trigger or mask the blocked-backlog page.
- count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(
+ stats = await DuckgresBatchQueue.get_backlog_stats(
conn, blocked_schema_ids=["schema-1"], failing_schema_ids=["schema-1"]
)
- assert (count, blocked, failing) == (0, 0, 1)
- assert blocked_age is None
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (0, 0, 1)
+ assert stats.blocked_oldest_age_seconds is None
# A failing schema whose batches are NOT blocked (still eligible) never
# counts in the failing bucket: failing splits the blocked set only.
- count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(
- conn, failing_schema_ids=["schema-1"]
- )
- assert (count, blocked, failing) == (1, 0, 0)
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn, failing_schema_ids=["schema-1"])
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (1, 0, 0)
# The v3 allow-list scopes the gauges too: a non-eligible schema drops
# out of both the eligible and blocked counts.
- count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(
- conn, eligible_schema_ids=["other-schema"]
- )
- assert (count, blocked, failing) == (0, 0, 0)
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn, eligible_schema_ids=["other-schema"])
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (0, 0, 0)
await _mark_applied_raw(conn, batch_id=batch_id, run_uuid="run-1", batch_index=0)
- count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(conn)
- assert (count, blocked, failing) == (0, 0, 0)
- assert oldest_age is None and blocked_age is None
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn)
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (0, 0, 0)
+ assert stats.eligible_oldest_age_seconds is None and stats.blocked_oldest_age_seconds is None
@pytest.mark.asyncio
async def test_backlog_stats_reflects_latest_delta_status_not_first(self, conn):
@@ -530,8 +524,8 @@ class TestDuckgresTeamFilterAndBacklog:
still_executing_id = await _insert_batch(conn, run_uuid="run-still-executing", batch_index=0)
await BatchQueue.update_status(conn, batch_id=still_executing_id, job_state="executing", attempt=1)
- count, _, blocked, _, failing = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=[1])
- assert (count, blocked, failing) == (1, 0, 0)
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=[1])
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (1, 0, 0)
class TestTeamScopeSargable:
@@ -571,11 +565,19 @@ class TestTeamScopeSargable:
team999_batch = await _insert_batch(conn, team_id=999, run_uuid="run-team-999", schema_id="schema-1")
await BatchQueue.update_status(conn, batch_id=team999_batch, job_state="succeeded", attempt=1)
- count, _, blocked, _, failing = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=[1])
- assert (count, blocked, failing) == (1, 0, 0) # team 999 excluded
-
- count, _, blocked, _, failing = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=None)
- assert (count, blocked, failing) == (2, 0, 0) # unscoped = all teams
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=[1])
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (
+ 1,
+ 0,
+ 0,
+ ) # team 999 excluded
+
+ stats = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=None)
+ assert (stats.eligible_count, stats.blocked_count, stats.failing_blocked_count) == (
+ 2,
+ 0,
+ 0,
+ ) # unscoped = all teams
@pytest.mark.django_db(transaction=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 4a3cff629594..518309e723a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -1,6 +1,6 @@
import time
import asyncio
-from typing import Any, Generic
+from typing import TYPE_CHECKING, Any, Generic
import pyarrow as pa
import posthoganalytics
@@ -80,6 +80,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
SourceResponse,
)
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
+ ImportJobModels,
+ )
+
PARQUET_COMPRESSION: ParquetCompression = "zstd"
@@ -111,11 +116,9 @@ class PipelineV3(Generic[ResumableData]):
job_id: str,
reset_pipeline: bool,
shutdown_monitor: ShutdownMonitor,
- job: ExternalDataJob,
- schema: ExternalDataSchema,
- source: ExternalDataSource,
- table: DataWarehouseTable | None,
resumable_source_manager: ResumableSourceManager[ResumableData] | None,
+ *,
+ models: "ImportJobModels",
) -> None:
self._resource = source_response
self._resource_name = source_response.name
@@ -123,19 +126,19 @@ class PipelineV3(Generic[ResumableData]):
# Persisted PK (user override or earlier detection) > live-detected > `id` fallback. Keeps
# the merge key stable across runs when live detection (e.g. Snowflake SHOW PRIMARY KEYS)
# intermittently returns nothing.
- self._resource.primary_keys = resolve_primary_keys(schema, self._resource)
+ self._resource.primary_keys = resolve_primary_keys(models.schema, self._resource)
- self._job = job
+ self._job = models.job
self._reset_pipeline = reset_pipeline
self._logger = logger
self._load_id = time.time_ns()
- self._schema = schema
- self._source = source
- self._table = table
+ self._schema = models.schema
+ self._source = models.source
+ self._table = models.table
# xmin reads deltas and upserts on the primary key, so it writes incrementally too — never
# as a full_refresh overwrite, which would wipe earlier data on the second (delta-only) sync.
- self._is_incremental = schema.is_incremental or schema.is_webhook or schema.is_xmin
+ self._is_incremental = models.schema.is_incremental or models.schema.is_webhook or models.schema.is_xmin
self._delta_table_ref = DeltaTableRef(self._resource_name, self._job, self._logger)
@@ -179,7 +182,7 @@ class PipelineV3(Generic[ResumableData]):
# SQL sources project enabled_columns in their SELECT and own schema_metadata via
# introspection; managed-schema sources don't allow selection. Everything else gets the
# write-side drop plus observed-columns capture so the column picker has a catalog.
- self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(source.source_type)
+ self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(models.source.source_type)
self._observed_columns: dict[str, dict[str, Any]] = {}
is_resume = resumable_source_manager is not None and resumable_source_manager.can_resume()
@@ -229,7 +232,7 @@ class PipelineV3(Generic[ResumableData]):
self._shutdown_monitor = shutdown_monitor
self._last_incremental_field_value: Any = None
self._earliest_incremental_field_value: Any = process_incremental_value(
- schema.incremental_field_earliest_value, schema.incremental_field_type
+ models.schema.incremental_field_earliest_value, models.schema.incremental_field_type
)
self._batch_results = []
@@ -447,10 +450,7 @@ class PipelineV3(Generic[ResumableData]):
if field.name not in self._accumulated_pa_schema.names:
self._accumulated_pa_schema = self._accumulated_pa_schema.append(field)
- (
- self._last_incremental_field_value,
- self._earliest_incremental_field_value,
- ) = await update_incremental_field_values(
+ incremental_values = await update_incremental_field_values(
self._schema,
pa_table,
self._resource,
@@ -460,6 +460,8 @@ class PipelineV3(Generic[ResumableData]):
log_prefix="V3 Pipeline: ",
staging_run_uuid=self._s3_batch_writer.get_run_uuid(),
)
+ self._last_incremental_field_value = incremental_values.last_value
+ self._earliest_incremental_field_value = incremental_values.earliest_value
await update_row_tracking_after_batch(
str(self._job.id), self._job.team_id, self._schema.id, pa_table.num_rows, self._logger
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index ee7891e4aec6..b05380eb46ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -4,6 +4,9 @@ import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
+ ImportJobModels,
+)
def _make_logger() -> MagicMock:
@@ -125,11 +128,8 @@ class TestAttemptScopedRunUuid:
job_id="job-1",
reset_pipeline=False,
shutdown_monitor=MagicMock(),
- job=mock_job,
- schema=mock_schema,
- source=mock_source,
- table=None,
resumable_source_manager=None,
+ models=ImportJobModels(job=mock_job, schema=mock_schema, source=mock_source, table=None),
)
assert pipeline._attempt == 3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
index e40413b20b42..6abbf1ce2746 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py
@@ -58,15 +58,15 @@ class TestResolveTableAndFolderNames:
def test_resolve(
self, _name: str, schema_name: str, resolved_folder: str | None, exp_table: str, exp_folder: str
) -> None:
- table_storage_name, folder_name = resolve_table_and_folder_names(schema_name, resolved_folder)
- assert table_storage_name == exp_table
- assert folder_name == exp_folder
+ names = resolve_table_and_folder_names(schema_name, resolved_folder)
+ assert names.table_storage_name == exp_table
+ assert names.folder_name == exp_folder
def test_table_name_unchanged_for_camelcase_source(self) -> None:
# The regression guard: a populated (snake_cased) folder must NOT rename the HogQL table.
source = ExternalDataSource(source_type="Stripe", prefix="")
- table_storage_name, _ = resolve_table_and_folder_names("BalanceTransaction", "balance_transaction")
- assert build_table_name(source, table_storage_name) == "stripe_balancetransaction"
+ names = resolve_table_and_folder_names("BalanceTransaction", "balance_transaction")
+ assert build_table_name(source, names.table_storage_name) == "stripe_balancetransaction"
@parameterized.expand(
[
@@ -83,8 +83,8 @@ class TestResolveTableAndFolderNames:
self, _name: str, source_type: str, schema_name: str, expected: str
) -> None:
source = ExternalDataSource(source_type=source_type, prefix="")
- table_storage_name, _ = resolve_table_and_folder_names(schema_name, None)
- assert build_table_name(source, table_storage_name) == expected
+ names = resolve_table_and_folder_names(schema_name, None)
+ assert build_table_name(source, names.table_storage_name) == expected
def _register_companion_sync(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.py
index feae444bb30a..b03af428f88a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_anal
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
# Adobe IMS issues the access token for OAuth Server-to-Server credentials. JWT ("Service
@@ -214,19 +215,21 @@ def resolve_window(
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
today: date,
-) -> tuple[date, date]:
+) -> SyncWindow[date]:
earliest = today - timedelta(days=MAX_BACKFILL_DAYS)
if should_use_incremental_field and db_incremental_field_last_value is not None:
last_value = parse_date(db_incremental_field_last_value)
if last_value is not None:
- return max(min(last_value - timedelta(days=INCREMENTAL_LOOKBACK_DAYS), today), earliest), today
+ return SyncWindow(
+ start=max(min(last_value - timedelta(days=INCREMENTAL_LOOKBACK_DAYS), today), earliest), end=today
+ )
configured = parse_date(start_date)
if configured is not None:
- return max(min(configured, today), earliest), today
+ return SyncWindow(start=max(min(configured, today), earliest), end=today)
- return today - timedelta(days=DEFAULT_BACKFILL_DAYS), today
+ return SyncWindow(start=today - timedelta(days=DEFAULT_BACKFILL_DAYS), end=today)
def build_report_body(
@@ -313,23 +316,23 @@ def _report_batches(
report_suite_id: str,
dimension: str,
metric_ids: list[str],
- start: date,
- end: date,
manager: ResumableSourceManager[AdobeAnalyticsResumeConfig],
resume: Optional[AdobeAnalyticsResumeConfig],
logger: FilteringBoundLogger,
+ *,
+ window: SyncWindow[date],
) -> Iterator[list[dict[str, Any]]]:
metric_columns = metric_column_names(metric_ids)
- current = start
+ current = window.start
page = 0
if resume is not None and resume.next_date:
resumed = parse_date(resume.next_date)
- if resumed is not None and start <= resumed <= end:
+ if resumed is not None and window.start <= resumed <= window.end:
current = resumed
page = resume.page
- while current <= end:
+ while current <= window.end:
while True:
payload = client.post_json(
"/reports", build_report_body(report_suite_id, dimension, metric_ids, current, page)
@@ -356,7 +359,7 @@ def _report_batches(
current += timedelta(days=1)
page = 0
- if current <= end:
+ if current <= window.end:
manager.save_state(AdobeAnalyticsResumeConfig(page=0, next_date=current.isoformat()))
manager.clear_state()
@@ -408,7 +411,7 @@ def get_rows(
yield from _metadata_batches(client, endpoint, report_suite_id, resumable_source_manager, resume)
return
- start, end = resolve_window(
+ window = resolve_window(
start_date,
should_use_incremental_field,
db_incremental_field_last_value,
@@ -419,11 +422,10 @@ def get_rows(
report_suite_id,
(report_dimension or DEFAULT_REPORT_DIMENSION).strip() or DEFAULT_REPORT_DIMENSION,
parse_metrics(report_metrics),
- start,
- end,
resumable_source_manager,
resume,
logger,
+ window=window,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py
index 3e283b58298c..bc32c6cc4c04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py
@@ -201,9 +201,9 @@ class TestResolveWindow:
self, start_date: str | None, incremental: bool, last_value: str | None, expected_start: date
) -> None:
today = date(2024, 3, 6)
- start, end = resolve_window(start_date, incremental, last_value, today)
- assert start == expected_start
- assert end == today
+ window = resolve_window(start_date, incremental, last_value, today)
+ assert window.start == expected_start
+ assert window.end == today
class TestBuildReportBody:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py
index 6f561a77acf5..951c7db72438 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/checkmarx.py
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.
CHECKMARX_ENDPOINTS,
CHECKMARX_REGION_HOSTS,
CheckmarxEndpointConfig,
+ RegionHosts,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -61,8 +62,8 @@ def _make_session(api_key: str) -> requests.Session:
return make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)
-def get_region_hosts(region: str) -> tuple[str, str]:
- """Return (api_base_url, iam_base_url) for a Checkmarx One region."""
+def get_region_hosts(region: str) -> RegionHosts:
+ """Return the API and IAM base URLs for a Checkmarx One region."""
hosts = CHECKMARX_REGION_HOSTS.get(region)
if hosts is None:
raise ValueError(f"Unknown Checkmarx One region: {region}")
@@ -331,17 +332,17 @@ def get_rows(
db_incremental_field_last_value: Any = None,
) -> Iterator[list[dict[str, Any]]]:
config = CHECKMARX_ENDPOINTS[endpoint]
- api_base_url, iam_base_url = get_region_hosts(region)
+ hosts = get_region_hosts(region)
# One session reused across every page (and, for fan-out, every scan) so urllib3 keeps the
# connection alive instead of re-handshaking per request.
session = _make_session(api_key)
- auth = CheckmarxAuth(session, iam_base_url, tenant_name, api_key)
+ auth = CheckmarxAuth(session, hosts.iam_base_url, tenant_name, api_key)
from_date = _build_incremental_value(config, should_use_incremental_field, db_incremental_field_last_value)
if config.fan_out_over_scans:
yield from _get_fan_out_rows(
- session, auth, api_base_url, endpoint, config, resumable_source_manager, from_date, logger
+ session, auth, hosts.api_base_url, endpoint, config, resumable_source_manager, from_date, logger
)
return
@@ -357,7 +358,7 @@ def get_rows(
for items, next_offset in _iter_pages(
session,
auth,
- f"{api_base_url}{config.path}",
+ f"{hosts.api_base_url}{config.path}",
params,
config.data_key,
config.page_size,
@@ -371,17 +372,17 @@ def get_rows(
def validate_credentials(tenant_name: str, region: str, api_key: str) -> tuple[bool, str | None]:
try:
- api_base_url, iam_base_url = get_region_hosts(region)
+ hosts = get_region_hosts(region)
except ValueError as e:
return False, str(e)
session = _make_session(api_key)
- auth = CheckmarxAuth(session, iam_base_url, tenant_name, api_key)
+ auth = CheckmarxAuth(session, hosts.iam_base_url, tenant_name, api_key)
try:
token = auth.get_token()
response = session.get(
- f"{api_base_url}/api/projects",
+ f"{hosts.api_base_url}/api/projects",
params={"offset": 0, "limit": 1},
headers={"Authorization": f"Bearer {token}", "Accept": "application/json; version=1.0"},
timeout=TOKEN_REQUEST_TIMEOUT,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py
index 0e93f90a5e45..cd8778400d55 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/settings.py
@@ -4,18 +4,25 @@ from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class RegionHosts:
+ api_base_url: str
+ iam_base_url: str
+
+
# Checkmarx One is deployed per region; both the API host and the IAM (auth) host vary with it.
# Region values match the documented multi-tenant deployments (https://checkmarx.com/resource/documents/en/34965-68630-checkmarx-one-regions.html).
-CHECKMARX_REGION_HOSTS: dict[str, tuple[str, str]] = {
- "us": ("https://ast.checkmarx.net", "https://iam.checkmarx.net"),
- "us2": ("https://us.ast.checkmarx.net", "https://us.iam.checkmarx.net"),
- "eu": ("https://eu.ast.checkmarx.net", "https://eu.iam.checkmarx.net"),
- "eu2": ("https://eu-2.ast.checkmarx.net", "https://eu-2.iam.checkmarx.net"),
- "deu": ("https://deu.ast.checkmarx.net", "https://deu.iam.checkmarx.net"),
- "anz": ("https://anz.ast.checkmarx.net", "https://anz.iam.checkmarx.net"),
- "ind": ("https://ind.ast.checkmarx.net", "https://ind.iam.checkmarx.net"),
- "sng": ("https://sng.ast.checkmarx.net", "https://sng.iam.checkmarx.net"),
- "mea": ("https://mea.ast.checkmarx.net", "https://mea.iam.checkmarx.net"),
+CHECKMARX_REGION_HOSTS: dict[str, RegionHosts] = {
+ "us": RegionHosts(api_base_url="https://ast.checkmarx.net", iam_base_url="https://iam.checkmarx.net"),
+ "us2": RegionHosts(api_base_url="https://us.ast.checkmarx.net", iam_base_url="https://us.iam.checkmarx.net"),
+ "eu": RegionHosts(api_base_url="https://eu.ast.checkmarx.net", iam_base_url="https://eu.iam.checkmarx.net"),
+ "eu2": RegionHosts(api_base_url="https://eu-2.ast.checkmarx.net", iam_base_url="https://eu-2.iam.checkmarx.net"),
+ "deu": RegionHosts(api_base_url="https://deu.ast.checkmarx.net", iam_base_url="https://deu.iam.checkmarx.net"),
+ "anz": RegionHosts(api_base_url="https://anz.ast.checkmarx.net", iam_base_url="https://anz.iam.checkmarx.net"),
+ "ind": RegionHosts(api_base_url="https://ind.ast.checkmarx.net", iam_base_url="https://ind.iam.checkmarx.net"),
+ "sng": RegionHosts(api_base_url="https://sng.ast.checkmarx.net", iam_base_url="https://sng.iam.checkmarx.net"),
+ "mea": RegionHosts(api_base_url="https://mea.ast.checkmarx.net", iam_base_url="https://mea.iam.checkmarx.net"),
}
_SCAN_CREATED_AT_INCREMENTAL_FIELD: IncrementalField = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py
index 5163432b0f1c..4ff8ad1ca6f2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkmarx/tests/test_checkmarx.py
@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.
from products.warehouse_sources.backend.temporal.data_imports.sources.checkmarx.settings import (
CHECKMARX_ENDPOINTS,
ENDPOINTS,
+ RegionHosts,
)
TOKEN_PAYLOAD = {"access_token": "jwt-token", "expires_in": 1800}
@@ -145,7 +146,7 @@ class TestCheckmarx:
],
)
def test_get_region_hosts(self, region: str, api_host: str, iam_host: str) -> None:
- assert get_region_hosts(region) == (api_host, iam_host)
+ assert get_region_hosts(region) == RegionHosts(api_base_url=api_host, iam_base_url=iam_host)
def test_get_region_hosts_unknown_region(self) -> None:
with pytest.raises(ValueError):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/location.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/location.py
index d7748b15b762..155da6ba1b1e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/location.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/location.py
@@ -6,6 +6,7 @@ delegates to, so the Postgres routing logic isn't re-derived per source.
from __future__ import annotations
+from dataclasses import dataclass
from typing import NamedTuple, Optional
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
@@ -35,9 +36,13 @@ def _str_or_none(value: object) -> Optional[str]:
return value if isinstance(value, str) else None
-def fill_missing_from_dotted_name(
- schema: Optional[str], table: Optional[str], display_name: str
-) -> tuple[Optional[str], Optional[str]]:
+@dataclass(frozen=True, kw_only=True, slots=True)
+class DottedNameParts:
+ schema: Optional[str]
+ table: Optional[str]
+
+
+def fill_missing_from_dotted_name(*, schema: Optional[str], table: Optional[str], display_name: str) -> DottedNameParts:
"""Fill a missing `schema`/`table` by splitting a dotted `display_name` (`analytics.users`).
Shared by the resolver and the migration so the rule can't drift between them.
@@ -46,7 +51,7 @@ def fill_missing_from_dotted_name(
inferred_schema, _, inferred_table = display_name.partition(".")
schema = schema or normalize_namespace(inferred_schema)
table = table or inferred_table or None
- return schema, table
+ return DottedNameParts(schema=schema, table=table)
def resolve_source_location(
@@ -64,12 +69,12 @@ def resolve_source_location(
metadata = inputs.schema_metadata if isinstance(inputs.schema_metadata, dict) else {}
source_schema = normalize_namespace(metadata.get("source_schema"))
source_table_name = _str_or_none(metadata.get("source_table_name"))
- source_schema, source_table_name = fill_missing_from_dotted_name(
- source_schema, source_table_name, inputs.schema_name
+ parts = fill_missing_from_dotted_name(
+ schema=source_schema, table=source_table_name, display_name=inputs.schema_name
)
- schema = source_schema or normalize_namespace(config_namespace) or default
- table_name = source_table_name or inputs.schema_name
+ schema = parts.schema or normalize_namespace(config_namespace) or default
+ table_name = parts.table or inputs.schema_name
storage_key = inputs.s3_folder_name if isinstance(inputs.s3_folder_name, str) and inputs.s3_folder_name else None
response_name = NamingConvention.normalize_identifier(storage_key or inputs.schema_name)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_location.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_location.py
index a6eacc0c5982..5fbe68438977 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_location.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/tests/test_location.py
@@ -5,6 +5,7 @@ from unittest.mock import MagicMock
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import (
+ DottedNameParts,
fill_missing_from_dotted_name,
normalize_namespace,
resolve_source_location,
@@ -155,4 +156,6 @@ class TestSelfHealHelpers:
exp_schema: str | None,
exp_table: str | None,
) -> None:
- assert fill_missing_from_dotted_name(schema, table, display_name) == (exp_schema, exp_table)
+ assert fill_missing_from_dotted_name(schema=schema, table=table, display_name=display_name) == DottedNameParts(
+ schema=exp_schema, table=exp_table
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sync_window.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sync_window.py
new file mode 100644
index 000000000000..321e90740542
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sync_window.py
@@ -0,0 +1,12 @@
+from dataclasses import dataclass
+from typing import Generic, TypeVar
+
+T = TypeVar("T")
+
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class SyncWindow(Generic[T]):
+ """Start/end bounds of one connector sync window; inclusivity of each bound is defined by the connector."""
+
+ start: T
+ end: T
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/confluent_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/confluent_cloud.py
index 253fd08d8f30..05a8ba436b3b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/confluent_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/confluent_cloud.py
@@ -10,6 +10,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.confluent_cloud.settings import (
CONFLUENT_CLOUD_BASE_URL,
@@ -211,7 +212,7 @@ def _sync_range(
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
now: datetime,
-) -> tuple[datetime, datetime]:
+) -> SyncWindow[datetime]:
retention_floor = now - timedelta(days=DEFAULT_LOOKBACK_DAYS)
start = retention_floor
if should_use_incremental_field:
@@ -220,7 +221,7 @@ def _sync_range(
# Cap a future-dated watermark at now, then re-pull a trailing overlap because recent
# buckets get restated; merge dedupes on the primary key. Never reach past retention.
start = max(min(watermark, now) - INCREMENTAL_OVERLAP, retention_floor)
- return start, now
+ return SyncWindow(start=start, end=now)
def _iter_metrics_rows(
@@ -241,13 +242,13 @@ def _iter_metrics_rows(
"Add the resource IDs in the source settings, or disable this table."
)
- start, end = _sync_range(should_use_incremental_field, db_incremental_field_last_value, datetime.now(UTC))
+ window = _sync_range(should_use_incremental_field, db_incremental_field_last_value, datetime.now(UTC))
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume is not None and resume.window_start:
resumed_start = _coerce_datetime(resume.window_start)
- if resumed_start is not None and start <= resumed_start < end:
- start = resumed_start
+ if resumed_start is not None and window.start <= resumed_start < window.end:
+ window = SyncWindow(start=resumed_start, end=window.end)
logger.debug(f"Confluent Cloud: resuming {endpoint} from window start {resume.window_start}")
metric_names = _get_metric_names(session, config.resource_type, logger)
@@ -255,9 +256,9 @@ def _iter_metrics_rows(
logger.warning(f"Confluent Cloud: no metrics found for resource type {config.resource_type}")
return
- window_start = start
- while window_start < end:
- window_end = min(window_start + QUERY_WINDOW, end)
+ window_start = window.start
+ while window_start < window.end:
+ window_end = min(window_start + QUERY_WINDOW, window.end)
interval = f"{_format_timestamp(window_start)}/{_format_timestamp(window_end)}"
for metric in metric_names:
@@ -269,7 +270,7 @@ def _iter_metrics_rows(
# Checkpoint AFTER the window's rows are yielded (and only while more windows remain), so a
# crash re-yields the current window rather than skipping it — merge dedupes on the primary
# key.
- if window_start < end:
+ if window_start < window.end:
resumable_source_manager.save_state(
ConfluentCloudResumeConfig(window_start=_format_timestamp(window_start))
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py
index a7a7aa9cf968..7e2c63ad9014 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/confluent_cloud/tests/test_confluent_cloud.py
@@ -68,9 +68,9 @@ class TestSyncRange:
]
)
def test_range(self, _name: str, incremental: bool, watermark: Any, expected_start: datetime) -> None:
- start, end = _sync_range(incremental, watermark, _NOW)
- assert start == expected_start
- assert end == _NOW
+ window = _sync_range(incremental, watermark, _NOW)
+ assert window.start == expected_start
+ assert window.end == _NOW
class TestBuildQueryBody:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
index 5640207d6c6d..bb8ef648cdce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/finnhub.py
@@ -8,6 +8,7 @@ from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.finnhub.settings import (
FINNHUB_ENDPOINTS,
@@ -116,14 +117,14 @@ def _extract_rows(data: Any, config: FinnhubEndpointConfig) -> list[dict[str, An
return data if isinstance(data, list) else []
-def _window(config: FinnhubEndpointConfig, last_value: Any) -> tuple[str, str]:
+def _window(config: FinnhubEndpointConfig, last_value: Any) -> SyncWindow[str]:
today = datetime.now(UTC).date()
if last_value is not None:
start = _to_date(last_value)
else:
start = today - timedelta(days=config.lookback_days)
end = today + timedelta(days=config.forward_days)
- return start.isoformat(), end.isoformat()
+ return SyncWindow(start=start.isoformat(), end=end.isoformat())
def _request_params(
@@ -143,7 +144,9 @@ def _request_params(
# Incremental endpoints advance `from` to the saved watermark; windowed full-refresh
# endpoints (calendars) always sweep the full rolling window.
last_value = db_incremental_field_last_value if should_use_incremental_field else None
- params["from"], params["to"] = _window(config, last_value)
+ window = _window(config, last_value)
+ params["from"] = window.start
+ params["to"] = window.end
return params
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
index 63625ab66f32..71d676d447fa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/finnhub/tests/test_finnhub.py
@@ -131,9 +131,9 @@ class TestRequestParams:
class TestWindow:
@freeze_time("2024-06-15")
def test_forward_days_extends_into_future(self) -> None:
- start, end = _window(FINNHUB_ENDPOINTS["earnings_calendar"], None)
- assert start == "2023-06-16"
- assert end == "2024-12-12"
+ window = _window(FINNHUB_ENDPOINTS["earnings_calendar"], None)
+ assert window.start == "2023-06-16"
+ assert window.end == "2024-12-12"
class TestGetRows:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.py
index af1a5e13925c..33d97e9da53a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.py
@@ -9,6 +9,7 @@ from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.gusto.settings import (
GUSTO_ENDPOINTS,
@@ -188,15 +189,15 @@ def list_companies(client: GustoClient) -> list[dict[str, Any]]:
return [companies[uuid] for uuid in sorted(companies)]
-def _window_bounds(db_incremental_field_last_value: Optional[Any]) -> tuple[str, str]:
+def _window_bounds(db_incremental_field_last_value: Optional[Any]) -> SyncWindow[str]:
end = (datetime.now(UTC).date() + timedelta(days=FUTURE_WINDOW_DAYS)).isoformat()
if db_incremental_field_last_value is None:
- return DEFAULT_WINDOW_START, end
+ return SyncWindow(start=DEFAULT_WINDOW_START, end=end)
raw = db_incremental_field_last_value
if isinstance(raw, datetime | date):
- return raw.isoformat()[:10], end
- return str(raw)[:10] or DEFAULT_WINDOW_START, end
+ return SyncWindow(start=raw.isoformat()[:10], end=end)
+ return SyncWindow(start=str(raw)[:10] or DEFAULT_WINDOW_START, end=end)
def _stamp_parents(rows: list[dict[str, Any]], parents: dict[str, str]) -> list[dict[str, Any]]:
@@ -329,10 +330,10 @@ def get_rows(
companies = list_companies(client)
if config.date_window_field is not None:
- start_date, end_date = _window_bounds(db_incremental_field_last_value)
+ window = _window_bounds(db_incremental_field_last_value)
# The whole window is buffered so it can be sorted, so there is no partial state worth
# checkpointing here — a retry simply re-requests the window.
- yield from _windowed_rows(client, config, companies, start_date, end_date)
+ yield from _windowed_rows(client, config, companies, window.start, window.end)
return
def checkpoint_page(company_index: int) -> Callable[[int], None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto.py
index be3e81abad88..f5677c44e87f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gusto/tests/test_gusto.py
@@ -270,10 +270,10 @@ class TestExtractRows:
class TestWindowBounds:
def test_defaults_to_full_history_without_a_watermark(self) -> None:
- start, end = _window_bounds(None)
- assert start == DEFAULT_WINDOW_START
+ window = _window_bounds(None)
+ assert window.start == DEFAULT_WINDOW_START
# The window reaches forward because payrolls and pay periods are scheduled ahead of today.
- assert end > datetime.now(UTC).date().isoformat()
+ assert window.end > datetime.now(UTC).date().isoformat()
@parameterized.expand(
[
@@ -284,7 +284,7 @@ class TestWindowBounds:
]
)
def test_watermark_becomes_the_window_start(self, _name: str, watermark: Any, expected: str) -> None:
- assert _window_bounds(watermark)[0] == expected
+ assert _window_bounds(watermark).start == expected
class TestGustoClient:
@@ -597,5 +597,5 @@ class TestValidateCredentials:
class TestWindowReach:
def test_future_window_covers_scheduled_pay_periods(self) -> None:
- _, end = _window_bounds(None)
- assert date.fromisoformat(end) > datetime.now(UTC).date() + timedelta(days=180)
+ window = _window_bounds(None)
+ assert date.fromisoformat(window.end) > datetime.now(UTC).date() + timedelta(days=180)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py
index e9225ee111f3..9abc3e91cfdf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py
@@ -10,6 +10,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.inngest.settings import (
INNGEST_DEFAULT_VERSION,
@@ -121,7 +122,7 @@ def _coerce_datetime(value: Any) -> datetime | None:
return None
-def _event_window(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> tuple[str, str]:
+def _event_window(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> SyncWindow[str]:
"""Compute the [received_after, received_before] RFC3339 window for a /v1/events walk.
`received_after` defaults to only 1 hour ago server-side, so it is always passed explicitly.
@@ -140,7 +141,7 @@ def _event_window(should_use_incremental_field: bool, db_incremental_field_last_
# forever; clamp it so the sync self-heals.
if after > now:
after = now
- return _format_rfc3339(after), _format_rfc3339(now)
+ return SyncWindow(start=_format_rfc3339(after), end=_format_rfc3339(now))
def _normalize_event(item: dict[str, Any]) -> dict[str, Any]:
@@ -182,18 +183,18 @@ def _iter_event_pages(
"""
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume is not None and resume.received_after and resume.received_before:
- received_after, received_before = resume.received_after, resume.received_before
+ window: SyncWindow[str] = SyncWindow(start=resume.received_after, end=resume.received_before)
cursor = resume.cursor
- logger.debug(f"Inngest: resuming events walk from cursor={cursor}, window ends {received_before}")
+ logger.debug(f"Inngest: resuming events walk from cursor={cursor}, window ends {window.end}")
else:
- received_after, received_before = _event_window(should_use_incremental_field, db_incremental_field_last_value)
+ window = _event_window(should_use_incremental_field, db_incremental_field_last_value)
cursor = None
while True:
params: dict[str, Any] = {
"limit": EVENTS_PAGE_SIZE,
- "received_after": received_after,
- "received_before": received_before,
+ "received_after": window.start,
+ "received_before": window.end,
}
if cursor:
params["cursor"] = cursor
@@ -210,7 +211,7 @@ def _iter_event_pages(
# treat it as the end of the walk.
has_more = len(items) == EVENTS_PAGE_SIZE and bool(next_cursor) and next_cursor != cursor
next_state = (
- InngestResumeConfig(cursor=next_cursor, received_after=received_after, received_before=received_before)
+ InngestResumeConfig(cursor=next_cursor, received_after=window.start, received_before=window.end)
if has_more
else None
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
index e95f1af7e53b..30e7836e2610 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/inngest/tests/test_inngest.py
@@ -66,9 +66,9 @@ class TestEventWindow:
def test_first_sync_backfills_the_max_retention_window(self) -> None:
# received_after defaults to only 1 hour ago server-side, so leaving it off a first sync
# would silently drop everything older than an hour.
- after, before = _event_window(should_use_incremental_field=False, db_incremental_field_last_value=None)
- assert after == "2026-04-15T12:00:00.000Z"
- assert before == "2026-07-14T12:00:00.000Z"
+ window = _event_window(should_use_incremental_field=False, db_incremental_field_last_value=None)
+ assert window.start == "2026-04-15T12:00:00.000Z"
+ assert window.end == "2026-07-14T12:00:00.000Z"
@parameterized.expand(
[
@@ -78,16 +78,16 @@ class TestEventWindow:
)
@freeze_time("2026-07-14T12:00:00Z")
def test_incremental_run_advances_from_the_watermark(self, _name: str, value: Any, expected_after: str) -> None:
- after, _ = _event_window(should_use_incremental_field=True, db_incremental_field_last_value=value)
- assert after == expected_after
+ window = _event_window(should_use_incremental_field=True, db_incremental_field_last_value=value)
+ assert window.start == expected_after
@freeze_time("2026-07-14T12:00:00Z")
def test_future_watermark_is_clamped_to_now(self) -> None:
# A future-dated watermark would produce an inverted window that returns nothing forever.
- after, before = _event_window(
+ window = _event_window(
should_use_incremental_field=True, db_incremental_field_last_value="2027-01-01T00:00:00Z"
)
- assert after == before == "2026-07-14T12:00:00.000Z"
+ assert window.start == window.end == "2026-07-14T12:00:00.000Z"
class TestEventsPagination:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py
index 2fdbfbef0397..2b7e1992e2cf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py
@@ -10,6 +10,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.settings import (
DEFAULT_BACKFILL_DAYS,
@@ -93,10 +94,10 @@ def _to_date(value: Any) -> Optional[date]:
return None
-def _day_window(day: date) -> tuple[str, str]:
+def _day_window(day: date) -> SyncWindow[str]:
start = f"{day.isoformat()}T00:00:00Z"
end = f"{(day + timedelta(days=1)).isoformat()}T00:00:00Z"
- return start, end
+ return SyncWindow(start=start, end=end)
def validate_credentials(host: str, api_key: Optional[str]) -> tuple[bool, str | None]:
@@ -131,13 +132,12 @@ def validate_credentials(host: str, api_key: Optional[str]) -> tuple[bool, str |
return True, None
-def _flatten_result_sets(data: Any, requested_window: tuple[str, str]) -> list[dict[str, Any]]:
+def _flatten_result_sets(data: Any, requested_window: SyncWindow[str]) -> list[dict[str, Any]]:
"""Flatten Allocation/Assets result sets (dicts keyed by allocation/asset name) into rows.
Windows with no data (e.g. beyond ETL retention) come back as ``data: [null]``,
so null/non-dict sets are skipped rather than treated as errors.
"""
- requested_start, requested_end = requested_window
rows: list[dict[str, Any]] = []
if not isinstance(data, list):
return rows
@@ -154,8 +154,8 @@ def _flatten_result_sets(data: Any, requested_window: tuple[str, str]) -> list[d
{
**item,
"key": key,
- "window_start": window.get("start") or requested_start,
- "window_end": window.get("end") or requested_end,
+ "window_start": window.get("start") or requested_window.start,
+ "window_end": window.get("end") or requested_window.end,
}
)
return rows
@@ -223,9 +223,9 @@ def get_rows(
day = start
while day <= today:
- window_start, window_end = _day_window(day)
- data = call(f"{window_start},{window_end}")
- rows = _flatten_result_sets(data, (window_start, window_end))
+ window = _day_window(day)
+ data = call(f"{window.start},{window.end}")
+ rows = _flatten_result_sets(data, window)
if rows:
yield rows
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py
index 2dded3fcf84b..f128f2e37940 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py
@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.mailersend.settings import MAILERSEND_ENDPOINTS
@@ -56,7 +57,7 @@ def _activity_date_window(
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
lookback_days: int,
-) -> tuple[int, int]:
+) -> SyncWindow[int]:
"""Build the required date_from/date_to window for the Activity endpoint as Unix timestamps.
MailerSend requires both bounds and rejects date_from >= date_to. On the first sync (or a full
@@ -74,7 +75,7 @@ def _activity_date_window(
# A future-dated cursor would make date_from >= date_to and 422 the request; clamp it.
date_from = now - timedelta(seconds=1)
- return int(date_from.timestamp()), int(now.timestamp())
+ return SyncWindow(start=int(date_from.timestamp()), end=int(now.timestamp()))
def check_credentials(api_token: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
@@ -143,7 +144,7 @@ def mailersend_source(
resumable_source_manager.save_state(MailerSendResumeConfig(fanout_state=state))
if config.fan_out_over_domains:
- date_from, date_to = _activity_date_window(
+ window = _activity_date_window(
should_use_incremental_field, db_incremental_field_last_value, config.default_lookback_days or 30
)
rest_config: RESTAPIConfig = {
@@ -171,8 +172,8 @@ def mailersend_source(
"limit": config.page_size,
# The window is computed once per run and rides as static query params —
# MailerSend filters server-side on created_at within [date_from, date_to].
- "date_from": date_from,
- "date_to": date_to,
+ "date_from": window.start,
+ "date_to": window.end,
},
"data_selector": "data",
},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
index 65c0c99271c3..d6e66825b0bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
@@ -104,38 +104,38 @@ class TestToDatetime:
class TestActivityDateWindow:
@freeze_time("2026-06-23T00:00:00Z")
def test_first_sync_uses_lookback_window(self) -> None:
- date_from, date_to = _activity_date_window(
+ window = _activity_date_window(
should_use_incremental_field=True, db_incremental_field_last_value=None, lookback_days=30
)
- assert date_to - date_from == 30 * 24 * 60 * 60
- assert date_to == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
+ assert window.end - window.start == 30 * 24 * 60 * 60
+ assert window.end == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
@freeze_time("2026-06-23T00:00:00Z")
def test_full_refresh_uses_lookback_window(self) -> None:
# Activity requires a date window even without an incremental cursor, so a full refresh still
# falls back to the lookback window rather than omitting the bounds.
- date_from, date_to = _activity_date_window(
+ window = _activity_date_window(
should_use_incremental_field=False, db_incremental_field_last_value=None, lookback_days=30
)
- assert date_to - date_from == 30 * 24 * 60 * 60
+ assert window.end - window.start == 30 * 24 * 60 * 60
@freeze_time("2026-06-23T00:00:00Z")
def test_incremental_starts_from_last_value(self) -> None:
last = datetime(2026, 6, 20, 12, 0, 0, tzinfo=UTC)
- date_from, date_to = _activity_date_window(
+ window = _activity_date_window(
should_use_incremental_field=True, db_incremental_field_last_value=last, lookback_days=30
)
- assert date_from == int(last.timestamp())
- assert date_to == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
+ assert window.start == int(last.timestamp())
+ assert window.end == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
@freeze_time("2026-06-23T00:00:00Z")
def test_future_cursor_is_clamped_below_date_to(self) -> None:
# A future-dated cursor would make date_from >= date_to and 422 the request; it must be clamped.
future = datetime(2027, 1, 1, tzinfo=UTC)
- date_from, date_to = _activity_date_window(
+ window = _activity_date_window(
should_use_incremental_field=True, db_incremental_field_last_value=future, lookback_days=30
)
- assert date_from < date_to
+ assert window.start < window.end
class TestCheckCredentials:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py
index 6689b5ffce0d..3665c74914d1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.s
MIXPANEL_API_VERSION_V1,
MIXPANEL_ENDPOINTS,
REGION_HOSTS,
+ RegionHosts,
)
# Rows buffered before yielding a batch. The pipeline batches again downstream, but
@@ -98,16 +99,16 @@ class MixpanelResumeConfig:
page: Optional[int] = None
-def _hosts(region: str) -> tuple[str, str]:
+def _hosts(region: str) -> RegionHosts:
return REGION_HOSTS.get(region, REGION_HOSTS["us"])
def _query_base(region: str) -> str:
- return _hosts(region)[0]
+ return _hosts(region).query_base
def _export_base(region: str) -> str:
- return _hosts(region)[1]
+ return _hosts(region).export_base
def _export_url(region: str, api_version: str) -> str:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py
index a6fb1be46c44..d963da381803 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py
@@ -30,12 +30,18 @@ class MixpanelRegion(StrEnum):
IN = "in"
-# region -> (query/app API base, raw export API base). Mixpanel splits the heavy raw
-# export traffic onto a separate `data*` host per data-residency region.
-REGION_HOSTS: dict[str, tuple[str, str]] = {
- MixpanelRegion.US: ("https://mixpanel.com", "https://data.mixpanel.com"),
- MixpanelRegion.EU: ("https://eu.mixpanel.com", "https://data-eu.mixpanel.com"),
- MixpanelRegion.IN: ("https://in.mixpanel.com", "https://data-in.mixpanel.com"),
+@dataclass(frozen=True, kw_only=True, slots=True)
+class RegionHosts:
+ query_base: str # query/app API base
+ export_base: str # raw export API base
+
+
+# Mixpanel splits the heavy raw export traffic onto a separate `data*` host per
+# data-residency region.
+REGION_HOSTS: dict[str, RegionHosts] = {
+ MixpanelRegion.US: RegionHosts(query_base="https://mixpanel.com", export_base="https://data.mixpanel.com"),
+ MixpanelRegion.EU: RegionHosts(query_base="https://eu.mixpanel.com", export_base="https://data-eu.mixpanel.com"),
+ MixpanelRegion.IN: RegionHosts(query_base="https://in.mixpanel.com", export_base="https://data-in.mixpanel.com"),
}
# First sync of the raw export endpoint only pulls this far back to avoid replaying
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
index a95f536cbfa9..5787dc019d8d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.settings import (
INSIGHTS_PAGE_SIZE,
@@ -128,7 +129,7 @@ def _to_utc_date(value: Any) -> date:
return parser.parse(str(value)).astimezone(UTC).date()
-def _insights_window(db_incremental_field_last_value: Optional[Any]) -> tuple[str, str]:
+def _insights_window(db_incremental_field_last_value: Optional[Any]) -> SyncWindow[str]:
"""The [since, until] ISO date window for one insights sync.
Incremental runs start at the watermark (the pipeline already rewinds it by the configured
@@ -140,7 +141,7 @@ def _insights_window(db_incremental_field_last_value: Optional[Any]) -> tuple[st
if db_incremental_field_last_value is not None:
since = _to_utc_date(db_incremental_field_last_value)
since = min(since, until)
- return since.isoformat(), until.isoformat()
+ return SyncWindow(start=since.isoformat(), end=until.isoformat())
def _convert_insights_times(row: dict[str, Any]) -> dict[str, Any]:
@@ -235,9 +236,9 @@ def openai_ads_source(
if config.aggregation_level is not None:
if resume is not None and resume.since and resume.until:
- since, until = resume.since, resume.until
+ window: SyncWindow[str] = SyncWindow(start=resume.since, end=resume.until)
else:
- since, until = _insights_window(db_incremental_field_last_value)
+ window = _insights_window(db_incremental_field_last_value)
params: dict[str, Any] = {
"aggregation_level": config.aggregation_level,
"time_granularity": "daily",
@@ -246,11 +247,13 @@ def openai_ads_source(
"fields[]": list(config.insights_fields),
# One JSON-encoded time-range object; the explicit timezone keeps daily buckets (and
# therefore the bucket ids merge dedupes on) stable across runs.
- "time_ranges[]": json.dumps({"type": "date_range", "since": since, "until": until, "timezone": "UTC"}),
+ "time_ranges[]": json.dumps(
+ {"type": "date_range", "since": window.start, "until": window.end, "timezone": "UTC"}
+ ),
}
data_map = _convert_insights_times
else:
- since = until = ""
+ window = SyncWindow(start="", end="")
# An explicit stable sort prevents page-boundary skips/duplicates while paginating the
# full campaign list.
params = {"limit": LIST_PAGE_SIZE, "order": "asc"}
@@ -288,7 +291,7 @@ def openai_ads_source(
# resumed cursor pairs with the result set it was issued for.
if state and state.get("cursor"):
resumable_source_manager.save_state(
- OpenAIAdsResumeConfig(cursor=state["cursor"], since=since or None, until=until or None)
+ OpenAIAdsResumeConfig(cursor=state["cursor"], since=window.start or None, until=window.end or None)
)
resource = rest_api_resource(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/plausible.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/plausible.py
index 6a84ab92b81b..0079bed35f18 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/plausible.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/plausible.py
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.plausible.settings import (
DEFAULT_BACKFILL_DAYS,
@@ -171,7 +172,7 @@ def _resolve_window(
resume_config: Optional[PlausibleResumeConfig],
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
-) -> tuple[date, date]:
+) -> SyncWindow[date]:
today = datetime.now(tz=UTC).date()
start = today - timedelta(days=DEFAULT_BACKFILL_DAYS)
if should_use_incremental_field:
@@ -192,7 +193,7 @@ def _resolve_window(
if start > end:
start = end
- return start, end
+ return SyncWindow(start=start, end=end)
def plausible_source(
@@ -209,8 +210,7 @@ def plausible_source(
config = PLAUSIBLE_ENDPOINTS[endpoint]
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- start, end = _resolve_window(resume_config, should_use_incremental_field, db_incremental_field_last_value)
- start_iso, end_iso = start.isoformat(), end.isoformat()
+ window = _resolve_window(resume_config, should_use_incremental_field, db_incremental_field_last_value)
initial_paginator_state: Optional[dict[str, Any]] = None
if resume_config is not None:
@@ -219,7 +219,7 @@ def plausible_source(
body: dict[str, Any] = {
"site_id": site_id,
"metrics": config.metrics,
- "date_range": [start_iso, end_iso],
+ "date_range": [window.start.isoformat(), window.end.isoformat()],
"dimensions": config.dimensions,
# Ascending by day so the pipeline's incremental watermark only ever advances forward.
"order_by": [["time:day", "asc"]],
@@ -256,7 +256,11 @@ def plausible_source(
# pinned so the resumed query keeps a consistent total_rows/ordering.
if state and state.get("offset") is not None:
resumable_source_manager.save_state(
- PlausibleResumeConfig(offset=int(state["offset"]), date_range_start=start_iso, date_range_end=end_iso)
+ PlausibleResumeConfig(
+ offset=int(state["offset"]),
+ date_range_start=window.start.isoformat(),
+ date_range_end=window.end.isoformat(),
+ )
)
resource = rest_api_resource(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/sage_hr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/sage_hr.py
index af816031a75b..3f3a74979ebe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/sage_hr.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/sage_hr.py
@@ -11,6 +11,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.settings import (
SAGE_HR_ENDPOINTS,
@@ -120,10 +121,10 @@ def _fetch_page(
return payload["data"], _extract_next_page(payload)
-def _leave_window_range() -> tuple[date, date]:
+def _leave_window_range() -> SyncWindow[date]:
"""Full date range the leave_requests sync covers: account prehistory through future bookings."""
today = datetime.now(UTC).date()
- return date.fromisoformat(LEAVE_WINDOW_START), today + timedelta(days=LEAVE_FUTURE_DAYS)
+ return SyncWindow(start=date.fromisoformat(LEAVE_WINDOW_START), end=today + timedelta(days=LEAVE_FUTURE_DAYS))
def _iter_windows(start: date, end: date) -> Iterator[tuple[date, date]]:
@@ -142,7 +143,7 @@ def _get_windowed_rows(
resumable_source_manager: ResumableSourceManager[SageHRResumeConfig],
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
- start, end = _leave_window_range()
+ window = _leave_window_range()
resume_from = date.fromisoformat(resume.window_from) if resume and resume.window_from else None
# The docs don't state whether `from`/`to` match on overlap or containment, so a request spanning
# a window boundary may come back from both windows. Full-refresh batches append without merging,
@@ -150,7 +151,7 @@ def _get_windowed_rows(
# boundary duplicate then persists until the next successful full sync replaces the table.)
seen_ids: set[Any] = set()
- for window_start, window_end in _iter_windows(start, end):
+ for window_start, window_end in _iter_windows(window.start, window.end):
if resume_from is not None and window_start < resume_from:
continue
@@ -189,7 +190,7 @@ def _get_windowed_rows(
# Window exhausted — everything up to it has been yielded, so a resume can skip straight to
# the next window.
next_window_start = window_end + timedelta(days=1)
- if next_window_start <= end:
+ if next_window_start <= window.end:
resumable_source_manager.save_state(
SageHRResumeConfig(next_page=1, window_from=next_window_start.isoformat())
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr.py
index b0272f703e34..3f45215398f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr.py
@@ -9,6 +9,7 @@ from unittest.mock import MagicMock
import requests
from parameterized import parameterized
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr import sage_hr
from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.sage_hr import (
SageHRResumeConfig,
@@ -208,7 +209,7 @@ class TestGetRows:
class TestWindowedLeaveRequests:
- RANGE = (date(2024, 1, 1), date(2024, 3, 31))
+ RANGE = SyncWindow(start=date(2024, 1, 1), end=date(2024, 3, 31))
def _collect(
self,
@@ -221,9 +222,9 @@ class TestWindowedLeaveRequests:
return TestGetRows._collect(manager, monkeypatch, pages, "leave_requests", requested)
def test_iter_windows_are_contiguous_and_capped(self) -> None:
- windows = list(_iter_windows(*self.RANGE))
- assert windows[0][0] == self.RANGE[0]
- assert windows[-1][1] == self.RANGE[1]
+ windows = list(_iter_windows(self.RANGE.start, self.RANGE.end))
+ assert windows[0][0] == self.RANGE.start
+ assert windows[-1][1] == self.RANGE.end
for window_start, window_end in windows:
# The API rejects `from`/`to` ranges of 65 days or more.
assert (window_end - window_start).days < 65
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
index 332a42501f7a..e38b8c7b9a09 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
IncrementalConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.settings import (
ALLOWED_SENTRY_API_BASE_URLS,
@@ -196,9 +197,9 @@ def _sentry_retention_incremental_window(cursor_path: str) -> IncrementalConfig:
}
-def _retention_window(incremental_value: Any = None) -> tuple[str, str]:
+def _retention_window(incremental_value: Any = None) -> SyncWindow[str]:
now = datetime.now(UTC)
- return _retention_bounded_start_param(incremental_value), _start_param_for_sentry(now)
+ return SyncWindow(start=_retention_bounded_start_param(incremental_value), end=_start_param_for_sentry(now))
def _parse_next_link(link_header: str) -> str | None:
@@ -638,7 +639,7 @@ def _iter_sessions_rows(
incremental_value: Any = None,
) -> Iterator[dict[str, Any]]:
"""Release health sessions, flattened to one row per interval per group."""
- start, end = _retention_window(incremental_value)
+ window = _retention_window(incremental_value)
payload = _fetch_json(
base_api_url,
_endpoint_path("sessions", organization_slug=organization_slug),
@@ -647,8 +648,8 @@ def _iter_sessions_rows(
"field": ["sum(session)", "count_unique(user)"],
"groupBy": ["project", "release", "environment", "session.status"],
"interval": "1d",
- "start": start,
- "end": end,
+ "start": window.start,
+ "end": window.end,
},
)
@@ -680,7 +681,7 @@ def _iter_organization_stats_rows(
single period total when it is, which would make the interval column meaningless.
Per-project volume lives in ``organization_stats_summary``.
"""
- start, end = _retention_window(incremental_value)
+ window = _retention_window(incremental_value)
payload = _fetch_json(
base_api_url,
_endpoint_path("organization_stats", organization_slug=organization_slug),
@@ -689,8 +690,8 @@ def _iter_organization_stats_rows(
"field": "sum(quantity)",
"groupBy": ["outcome", "category", "reason"],
"interval": "1d",
- "start": start,
- "end": end,
+ "start": window.start,
+ "end": window.end,
},
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/signoz.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/signoz.py
index eb8a0c62c879..e61c29da42fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/signoz.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/signoz.py
@@ -11,6 +11,7 @@ from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.settings import (
SIGNOZ_ENDPOINTS,
@@ -150,13 +151,13 @@ def validate_credentials(
def _build_query_range_body(
config: SigNozEndpointConfig,
- window_start_ms: int,
- window_end_ms: int,
offset: int,
+ *,
+ window: SyncWindow[int],
) -> dict[str, Any]:
return {
- "start": window_start_ms,
- "end": window_end_ms,
+ "start": window.start,
+ "end": window.end,
"requestType": "raw",
"compositeQuery": {
"queries": [
@@ -240,7 +241,7 @@ def _initial_window(
config: SigNozEndpointConfig,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
-) -> tuple[int, int]:
+) -> SyncWindow[int]:
end_ms = int(datetime.now(UTC).timestamp() * 1000)
start_ms: int | None = None
if should_use_incremental_field and db_incremental_field_last_value is not None:
@@ -248,7 +249,7 @@ def _initial_window(
if start_ms is None:
lookback_days = config.default_lookback_days or DEFAULT_LOOKBACK_DAYS
start_ms = int((datetime.now(UTC) - timedelta(days=lookback_days)).timestamp() * 1000)
- return start_ms, end_ms
+ return SyncWindow(start=start_ms, end=end_ms)
def get_rows(
@@ -318,18 +319,17 @@ def get_rows(
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume is not None:
- window_start, window_end, offset = resume.window_start_ms, resume.window_end_ms, resume.offset
- logger.debug(f"SigNoz: resuming {endpoint} at window_start={window_start}, offset={offset}")
+ window: SyncWindow[int] = SyncWindow(start=resume.window_start_ms, end=resume.window_end_ms)
+ offset = resume.offset
+ logger.debug(f"SigNoz: resuming {endpoint} at window_start={window.start}, offset={offset}")
else:
- window_start, window_end = _initial_window(
- config, should_use_incremental_field, db_incremental_field_last_value
- )
+ window = _initial_window(config, should_use_incremental_field, db_incremental_field_last_value)
offset = 0
url = f"{base}{QUERY_RANGE_PATH}"
while True:
- body = _build_query_range_body(config, window_start, window_end, offset)
+ body = _build_query_range_body(config, offset, window=window)
rows = _extract_raw_rows(fetch(url, json_body=body))
if not rows:
break
@@ -345,10 +345,10 @@ def get_rows(
# the last row's millisecond are re-listed on the next request and skipped via the
# offset; anything re-yielded across a crash is deduped by primary-key merge.
last_ts = _to_epoch_ms(rows[-1].get("timestamp"))
- if last_ts is None or last_ts < window_start:
+ if last_ts is None or last_ts < window.start:
# No usable timestamp to advance on — fall back to plain offset paging.
offset += len(rows)
- elif last_ts == window_start:
+ elif last_ts == window.start:
# The entire window start millisecond spans multiple pages.
offset += len(rows)
else:
@@ -358,13 +358,13 @@ def get_rows(
trailing += 1
else:
break
- window_start = last_ts
+ window = SyncWindow(start=last_ts, end=window.end)
offset = trailing
# Save state AFTER yielding the batch — a crash re-yields the last batch (merge
# dedupes on primary key) instead of skipping it.
resumable_source_manager.save_state(
- SigNozResumeConfig(window_start_ms=window_start, window_end_ms=window_end, offset=offset)
+ SigNozResumeConfig(window_start_ms=window.start, window_end_ms=window.end, offset=offset)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz.py b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz.py
index 9e231f148191..9b89f6a5e4f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/signoz/tests/test_signoz.py
@@ -7,6 +7,7 @@ from unittest import mock
import requests
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.signoz import signoz as sgz
from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.settings import SIGNOZ_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.signoz.signoz import (
@@ -59,7 +60,7 @@ class TestToEpochMs:
class TestBuildQueryRangeBody:
def test_logs_body_shape(self) -> None:
- body = _build_query_range_body(SIGNOZ_ENDPOINTS["logs"], 1000, 2000, 50)
+ body = _build_query_range_body(SIGNOZ_ENDPOINTS["logs"], 50, window=SyncWindow(start=1000, end=2000))
assert body["start"] == 1000
assert body["end"] == 2000
@@ -76,7 +77,7 @@ class TestBuildQueryRangeBody:
]
def test_traces_order_uses_span_id_tiebreaker(self) -> None:
- body = _build_query_range_body(SIGNOZ_ENDPOINTS["traces"], 0, 1, 0)
+ body = _build_query_range_body(SIGNOZ_ENDPOINTS["traces"], 0, window=SyncWindow(start=0, end=1))
spec = body["compositeQuery"]["queries"][0]["spec"]
assert spec["signal"] == "traces"
assert [o["key"]["name"] for o in spec["order"]] == ["timestamp", "span_id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.py
index 7ecb83a15a0a..820b4bacaa70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/snowplow.py
@@ -9,6 +9,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.snowplow.settings import (
SNOWPLOW_ENDPOINTS,
@@ -196,7 +197,7 @@ def _jobs_window_bounds(
db_incremental_field_last_value: Any,
resume_window_from: str | None,
now: datetime,
-) -> tuple[datetime, datetime]:
+) -> SyncWindow[datetime]:
"""Compute the overall (from, to) range to slice for the jobs endpoints.
Runs are only retained for about a week, so both first syncs and stale watermarks clamp to
@@ -212,7 +213,7 @@ def _jobs_window_bounds(
start = max(start, floor)
if start > now:
start = now
- return start, now
+ return SyncWindow(start=start, end=now)
def _get_windowed_job_rows(
@@ -224,14 +225,14 @@ def _get_windowed_job_rows(
db_incremental_field_last_value: Any,
) -> Iterator[list[dict[str, Any]]]:
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- start, end = _jobs_window_bounds(
+ window = _jobs_window_bounds(
should_use_incremental_field,
db_incremental_field_last_value,
resume.window_from if resume else None,
now=datetime.now(UTC),
)
- for window_start, window_end in _iter_windows(start, end, JOB_RUNS_WINDOW):
+ for window_start, window_end in _iter_windows(window.start, window.end, JOB_RUNS_WINDOW):
runs = client.get(
"/jobs/v1/runs", params={"from": _format_datetime(window_start), "to": _format_datetime(window_end)}
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py
index 11b236da8e80..97d612c06e72 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowplow/tests/test_snowplow.py
@@ -98,59 +98,59 @@ class TestWindows:
@freeze_time("2026-07-15T12:00:00Z")
def test_first_sync_starts_at_the_retention_floor(self) -> None:
# Snowplow only keeps about a week of runs; asking for more gets the window rejected.
- start, end = _jobs_window_bounds(
+ window = _jobs_window_bounds(
should_use_incremental_field=False,
db_incremental_field_last_value=None,
resume_window_from=None,
now=datetime.now(UTC),
)
- assert end == datetime(2026, 7, 15, 12, tzinfo=UTC)
- assert start == end - snowplow.JOB_RUNS_RETENTION
+ assert window.end == datetime(2026, 7, 15, 12, tzinfo=UTC)
+ assert window.start == window.end - snowplow.JOB_RUNS_RETENTION
@freeze_time("2026-07-15T12:00:00Z")
def test_incremental_run_rewinds_watermark_by_lookback(self) -> None:
# A run listed while RUNNING changes state after we fetch it; advancing straight from the
# watermark would freeze it at RUNNING forever.
- start, _ = _jobs_window_bounds(
+ window = _jobs_window_bounds(
should_use_incremental_field=True,
db_incremental_field_last_value="2026-07-15T00:00:00Z",
resume_window_from=None,
now=datetime.now(UTC),
)
- assert start == datetime(2026, 7, 14, tzinfo=UTC)
+ assert window.start == datetime(2026, 7, 14, tzinfo=UTC)
@freeze_time("2026-07-15T12:00:00Z")
def test_stale_watermark_is_clamped_to_the_retention_floor(self) -> None:
# A watermark older than the retention window would produce a from the API rejects.
- start, end = _jobs_window_bounds(
+ window = _jobs_window_bounds(
should_use_incremental_field=True,
db_incremental_field_last_value="2026-06-01T00:00:00Z",
resume_window_from=None,
now=datetime.now(UTC),
)
- assert start == end - snowplow.JOB_RUNS_RETENTION
+ assert window.start == window.end - snowplow.JOB_RUNS_RETENTION
@freeze_time("2026-07-15T12:00:00Z")
def test_future_watermark_is_clamped_to_now(self) -> None:
- start, end = _jobs_window_bounds(
+ window = _jobs_window_bounds(
should_use_incremental_field=True,
db_incremental_field_last_value="2026-08-01T00:00:00Z",
resume_window_from=None,
now=datetime.now(UTC),
)
- assert start == end
+ assert window.start == window.end
@freeze_time("2026-07-15T12:00:00Z")
def test_resume_window_takes_precedence_over_the_watermark(self) -> None:
# On resume the saved window marks what was already yielded; restarting from the watermark
# would re-fetch (and re-merge) everything the crashed attempt already produced.
- start, _ = _jobs_window_bounds(
+ window = _jobs_window_bounds(
should_use_incremental_field=True,
db_incremental_field_last_value="2026-07-10T00:00:00Z",
resume_window_from="2026-07-14T12:00:00Z",
now=datetime.now(UTC),
)
- assert start == datetime(2026, 7, 14, 12, tzinfo=UTC)
+ assert window.start == datetime(2026, 7, 14, 12, tzinfo=UTC)
class TestJobRuns:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/squadcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/squadcast.py
index 282fb57a4fe8..756b57e7cd9a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/squadcast.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/squadcast/squadcast.py
@@ -17,11 +17,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.squadcast.
SquadcastEndpointConfig,
)
+
[email protected](frozen=True, kw_only=True, slots=True)
+class RegionHosts:
+ auth_host: str
+ api_host: str
+
+
# Squadcast is region-sharded: a US account's refresh token only works against the US hosts and
# vice versa, so the user picks the region in the source form.
-REGION_HOSTS: dict[str, tuple[str, str]] = {
- "us": ("https://auth.squadcast.com", "https://api.squadcast.com"),
- "eu": ("https://auth.eu.squadcast.com", "https://api.eu.squadcast.com"),
+REGION_HOSTS: dict[str, RegionHosts] = {
+ "us": RegionHosts(auth_host="https://auth.squadcast.com", api_host="https://api.squadcast.com"),
+ "eu": RegionHosts(auth_host="https://auth.eu.squadcast.com", api_host="https://api.eu.squadcast.com"),
}
PAGE_SIZE = 100
@@ -64,7 +71,7 @@ class SquadcastResumeConfig:
cursor: str | None = None
-def _hosts_for_region(region: str | None) -> tuple[str, str]:
+def _hosts_for_region(region: str | None) -> RegionHosts:
return REGION_HOSTS.get((region or "us").lower(), REGION_HOSTS["us"])
@@ -99,7 +106,9 @@ class SquadcastClient:
bearer access token and transparently re-exchanges it before expiry."""
def __init__(self, refresh_token: str, region: str | None, logger: FilteringBoundLogger) -> None:
- self._auth_host, self.api_host = _hosts_for_region(region)
+ hosts = _hosts_for_region(region)
+ self._auth_host = hosts.auth_host
+ self.api_host = hosts.api_host
self._refresh_token = refresh_token
self._logger = logger
# Sessions are reused across requests so urllib3 keeps the connection alive. The refresh
@@ -472,7 +481,7 @@ def validate_credentials(
Returns ``(ok, status_code, error_message)``. ``status_code`` is 0 on transport failure.
The caller decides how to treat 403 (valid token, missing access for the probed endpoint).
"""
- auth_host, api_host = _hosts_for_region(region)
+ hosts = _hosts_for_region(region)
# Same credential hardening as SquadcastClient: mask the refresh token, never follow
# redirects with credentialed headers, and keep both the token exchange and the API probe
# out of sample capture — the probe response body carries customer operational data.
@@ -481,7 +490,7 @@ def validate_credentials(
try:
auth_response = auth_session.get(
- f"{auth_host}/oauth/access-token",
+ f"{hosts.auth_host}/oauth/access-token",
headers={"X-Refresh-Token": refresh_token},
timeout=10,
)
@@ -504,7 +513,7 @@ def validate_credentials(
try:
response = session.get(
- f"{api_host}{probe_path}",
+ f"{hosts.api_host}{probe_path}",
headers={"Authorization": f"Bearer {access_token}"},
timeout=10,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tempo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tempo.py
index c7e8e6fafc83..54c98ed9d5cb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tempo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tempo.py
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.settings import (
TEMPO_ENDPOINTS,
@@ -46,9 +47,9 @@ def _headers(api_token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}
-def _plans_window() -> tuple[str, str]:
+def _plans_window() -> SyncWindow[str]:
end = date.today() + timedelta(days=365 * PLANS_WINDOW_YEARS_AHEAD)
- return PLANS_WINDOW_START, end.isoformat()
+ return SyncWindow(start=PLANS_WINDOW_START, end=end.isoformat())
def _format_updated_from(value: Any) -> str:
@@ -84,9 +85,9 @@ def _build_initial_params(
if config.paginated:
params["limit"] = PAGE_SIZE
if config.requires_date_window:
- window_from, window_to = _plans_window()
- params["from"] = window_from
- params["to"] = window_to
+ window = _plans_window()
+ params["from"] = window.start
+ params["to"] = window.end
if config.order_by:
params["orderBy"] = config.order_by
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py
index 32642922b9f7..eae6934d3cc2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.settings import (
BASE_URL,
@@ -170,17 +171,17 @@ def _iter_chunk(
return resource
-def _get_chunk_dates(chunk_resource: dict[str, Any]) -> tuple[Optional[str], Optional[str]]:
- """Extract the chunk's ``(start_date, end_date)`` params, or ``(None, None)``."""
+def _get_chunk_dates(chunk_resource: dict[str, Any]) -> SyncWindow[Optional[str]]:
+ """Extract the chunk's ``start_date``/``end_date`` params (``None`` when absent)."""
endpoint_cfg = chunk_resource.get("endpoint")
if not isinstance(endpoint_cfg, dict):
- return None, None
+ return SyncWindow(start=None, end=None)
params = endpoint_cfg.get("params")
if not isinstance(params, dict):
- return None, None
+ return SyncWindow(start=None, end=None)
start = params.get("start_date")
end = params.get("end_date")
- return (start if isinstance(start, str) else None, end if isinstance(end, str) else None)
+ return SyncWindow(start=start if isinstance(start, str) else None, end=end if isinstance(end, str) else None)
def _resolve_resume_chunk_index(loaded: TikTokAdsResumeConfig, chunk_resources: list[dict[str, Any]]) -> Optional[int]:
@@ -198,8 +199,8 @@ def _resolve_resume_chunk_index(loaded: TikTokAdsResumeConfig, chunk_resources:
return None
for idx, chunk in enumerate(chunk_resources):
- start, end = _get_chunk_dates(chunk)
- if start == loaded.chunk_start_date and end == loaded.chunk_end_date:
+ window = _get_chunk_dates(chunk)
+ if window.start == loaded.chunk_start_date and window.end == loaded.chunk_end_date:
return idx
return None
@@ -245,10 +246,10 @@ def tiktok_ads_source(
if resumed_chunk_index is not None and chunk_index == resumed_chunk_index:
initial_paginator_state = {"page": resumed_page}
- chunk_start, chunk_end = _get_chunk_dates(chunk_resource)
+ chunk_window = _get_chunk_dates(chunk_resource)
def make_save_checkpoint(
- idx: int, start: Optional[str], end: Optional[str]
+ idx: int, *, window: SyncWindow[Optional[str]]
) -> Callable[[Optional[dict[str, Any]]], None]:
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# The paginator only emits state while there are pages
@@ -259,8 +260,8 @@ def tiktok_ads_source(
TikTokAdsResumeConfig(
page=int(state["page"]),
chunk_index=idx,
- chunk_start_date=start,
- chunk_end_date=end,
+ chunk_start_date=window.start,
+ chunk_end_date=window.end,
)
)
@@ -273,7 +274,7 @@ def tiktok_ads_source(
job_id,
db_incremental_field_last_value,
initial_paginator_state,
- make_save_checkpoint(chunk_index, chunk_start, chunk_end),
+ make_save_checkpoint(chunk_index, window=chunk_window),
)
flat = TikTokReportResource.process_resources([resource])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py
index c5361e597c97..6c4bb283d97f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.z
MAX_PAGE,
PAGE_SIZE,
REFRESH_TOKEN_REJECTED_MESSAGE,
+ RegionHosts,
ZohoCRMAuthError,
ZohoCRMClient,
ZohoCRMResumeConfig,
@@ -113,7 +114,7 @@ class TestResolveHosts:
],
)
def test_regional_hosts(self, region: str, accounts_host: str, api_host: str) -> None:
- assert resolve_hosts(region) == (accounts_host, api_host)
+ assert resolve_hosts(region) == RegionHosts(accounts_host=accounts_host, api_domain=api_host)
def test_unknown_region_raises(self) -> None:
with pytest.raises(ValueError):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py
index 9062baeedf38..1eacdb111f38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py
@@ -19,17 +19,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.s
DEFAULT_API_VERSION = "v8"
+
[email protected](frozen=True, kw_only=True, slots=True)
+class RegionHosts:
+ accounts_host: str
+ api_domain: str
+
+
# Zoho accounts are pinned to one data center; the accounts host mints the token and the
# API host serves the records. The token response also names the account's real API domain,
# which wins over this mapping when present.
-ZOHO_REGIONS: dict[str, tuple[str, str]] = {
- "us": ("https://accounts.zoho.com", "https://www.zohoapis.com"),
- "eu": ("https://accounts.zoho.eu", "https://www.zohoapis.eu"),
- "in": ("https://accounts.zoho.in", "https://www.zohoapis.in"),
- "au": ("https://accounts.zoho.com.au", "https://www.zohoapis.com.au"),
- "jp": ("https://accounts.zoho.jp", "https://www.zohoapis.jp"),
- "ca": ("https://accounts.zohocloud.ca", "https://www.zohoapis.ca"),
- "cn": ("https://accounts.zoho.com.cn", "https://www.zohoapis.com.cn"),
+ZOHO_REGIONS: dict[str, RegionHosts] = {
+ "us": RegionHosts(accounts_host="https://accounts.zoho.com", api_domain="https://www.zohoapis.com"),
+ "eu": RegionHosts(accounts_host="https://accounts.zoho.eu", api_domain="https://www.zohoapis.eu"),
+ "in": RegionHosts(accounts_host="https://accounts.zoho.in", api_domain="https://www.zohoapis.in"),
+ "au": RegionHosts(accounts_host="https://accounts.zoho.com.au", api_domain="https://www.zohoapis.com.au"),
+ "jp": RegionHosts(accounts_host="https://accounts.zoho.jp", api_domain="https://www.zohoapis.jp"),
+ "ca": RegionHosts(accounts_host="https://accounts.zohocloud.ca", api_domain="https://www.zohoapis.ca"),
+ "cn": RegionHosts(accounts_host="https://accounts.zoho.com.cn", api_domain="https://www.zohoapis.com.cn"),
}
# Zoho caps `per_page` at 200.
@@ -62,7 +69,7 @@ class ZohoCRMResumeConfig:
page_tokens: list[str] = dataclasses.field(default_factory=list)
-def resolve_hosts(region: str) -> tuple[str, str]:
+def resolve_hosts(region: str) -> RegionHosts:
hosts = ZOHO_REGIONS.get(region)
if hosts is None:
raise ValueError(f"Invalid Zoho CRM region: {region}")
@@ -97,7 +104,11 @@ class ZohoCRMClient:
client_secret: str,
refresh_token: str,
) -> None:
- self._accounts_host, self._api_domain = resolve_hosts(region)
+ hosts = resolve_hosts(region)
+ self._accounts_host = hosts.accounts_host
+ # Instance attribute (not the frozen hosts value) because the token response's
+ # `api_domain` overrides it after auth.
+ self._api_domain = hosts.api_domain
self._client_id = client_id
self._client_secret = client_secret
self._refresh_token = refresh_token
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
index c87581af6697..28aaed820d75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
@@ -162,8 +162,8 @@ def _take_over_lock_if_holder_finished(inputs: AcquireV3LockActivityInputs, toke
holder_age_seconds = _holder_token_age_seconds(holder)
# Step 1: check if the holder's Temporal workflow is still running
- workflow_status, holder_job, status_is_assumed = _describe_holder_workflow(inputs, holder, meta_workflow_id, logger)
- if workflow_status is None:
+ description = _describe_holder_workflow(inputs, holder, meta_workflow_id, logger)
+ if description.status is None:
# Describe failed - fail closed (ambiguous)
logger.warning(
"v3_pipeline_lock_takeover_ambiguous",
@@ -175,8 +175,8 @@ def _take_over_lock_if_holder_finished(inputs: AcquireV3LockActivityInputs, toke
)
return False
- if workflow_status == WorkflowExecutionStatus.RUNNING:
- if holder_job is None:
+ if description.status == WorkflowExecutionStatus.RUNNING:
+ if description.job is None:
# Near-miss race: a healthy holder still pre-job-row — log so these
# show up in prod.
logger.info(
@@ -190,9 +190,9 @@ def _take_over_lock_if_holder_finished(inputs: AcquireV3LockActivityInputs, toke
return False
# Step 2/3: workflow is terminal, check the job row
- if holder_job is None:
+ if description.job is None:
if (
- status_is_assumed
+ description.status_is_assumed
and holder_age_seconds is not None
and holder_age_seconds < NO_JOB_ROW_TAKEOVER_GRACE_SECONDS
):
@@ -215,24 +215,24 @@ def _take_over_lock_if_holder_finished(inputs: AcquireV3LockActivityInputs, toke
reason="no_job_row",
holder_age_seconds=holder_age_seconds,
meta_found=meta_found,
- holder_status_assumed=status_is_assumed,
+ holder_status_assumed=description.status_is_assumed,
)
return _release_and_acquire(inputs, holder, token)
- if holder_job.status in TERMINAL_JOB_STATUSES:
+ if description.job.status in TERMINAL_JOB_STATUSES:
logger.warning(
"v3_pipeline_lock_taking_over",
schema_id=str(inputs.schema_id),
holder_token=holder,
reason="job_terminal",
- holder_job_status=holder_job.status,
+ holder_job_status=description.job.status,
holder_age_seconds=holder_age_seconds,
meta_found=meta_found,
)
return _release_and_acquire(inputs, holder, token)
# Step 4: workflow terminal but job still RUNNING - consult queue DB
- return _take_over_stale_running_job(inputs, holder, token, holder_job, logger)
+ return _take_over_stale_running_job(inputs, holder, token, description.job, logger)
def _holder_token_age_seconds(token: str) -> float | None:
@@ -249,14 +249,21 @@ def _holder_token_age_seconds(token: str) -> float | None:
return round(age, 1)
[email protected](frozen=True, kw_only=True, slots=True)
+class HolderWorkflowDescription:
+ status: WorkflowExecutionStatus | None
+ job: ExternalDataJob | None
+ status_is_assumed: bool
+
+
def _describe_holder_workflow(
inputs: AcquireV3LockActivityInputs,
holder_run_id: str,
meta_workflow_id: str | None,
logger: Any,
-) -> tuple[WorkflowExecutionStatus | None, ExternalDataJob | None, bool]:
- """Return (status, job, status_is_assumed): assumed=True when no workflow_id
- exists anywhere so TERMINATED is a guess; (None, None, False) on describe error."""
+) -> HolderWorkflowDescription:
+ """status_is_assumed=True when no workflow_id exists anywhere so TERMINATED is
+ a guess; status=None on describe error."""
try:
holder_job = (
ExternalDataJob.objects.filter(
@@ -270,12 +277,14 @@ def _describe_holder_workflow(
)
workflow_id = (holder_job.workflow_id if holder_job is not None else None) or meta_workflow_id
if not workflow_id:
- return WorkflowExecutionStatus.TERMINATED, holder_job, True
+ return HolderWorkflowDescription(
+ status=WorkflowExecutionStatus.TERMINATED, job=holder_job, status_is_assumed=True
+ )
temporal: Client = sync_connect()
handle = temporal.get_workflow_handle(workflow_id, run_id=holder_run_id)
desc = async_to_sync(handle.describe)()
- return desc.status, holder_job, False
+ return HolderWorkflowDescription(status=desc.status, job=holder_job, status_is_assumed=False)
except Exception as e:
logger.warning(
"v3_pipeline_lock_describe_failed",
@@ -284,7 +293,7 @@ def _describe_holder_workflow(
error=str(e),
)
capture_exception(e)
- return None, None, False
+ return HolderWorkflowDescription(status=None, job=None, status_is_assumed=False)
def _take_over_stale_running_job(
diff --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.py
index 5bfaac7f0549..ac3c08629e7f 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
@@ -305,10 +305,18 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
raise ValueError(f"Source type {model.pipeline.source_type} not supported")
[email protected](frozen=True, kw_only=True, slots=True)
+class ImportJobModels:
+ job: ExternalDataJob
+ schema: ExternalDataSchema
+ source: ExternalDataSource
+ table: DataWarehouseTable | None
+
+
@database_sync_to_async_pool
def _get_models(
job_id: str,
-) -> tuple[ExternalDataJob, ExternalDataSchema, ExternalDataSource, DataWarehouseTable | None]:
+) -> ImportJobModels:
# `schema__source` is prefetched so `job.folder_path()` (via `schema.source.source_type`, called
# repeatedly through the run by `DeltaTableRef._get_delta_table_uri`) never triggers a lazy
# relation load later on a pooled connection the transaction pooler may have dropped mid-sync,
@@ -322,7 +330,7 @@ def _get_models(
raise Exception("No source attached to job")
table: DataWarehouseTable | None = schema.table
- return job, schema, source, table
+ return ImportJobModels(job=job, schema=schema, source=source, table=table)
async def _handle_import_error(
@@ -448,9 +456,9 @@ async def _run(
resumable_source_manager: ResumableSourceManager | None,
) -> PipelineResult:
try:
- job, schema, source, table = await _get_models(job_inputs.run_id)
+ models = await _get_models(job_inputs.run_id)
- use_v3 = job.pipeline_version == ExternalDataJob.PipelineVersion.V3
+ use_v3 = models.job.pipeline_version == ExternalDataJob.PipelineVersion.V3
if use_v3:
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import PipelineV3
@@ -462,11 +470,8 @@ async def _run(
job_inputs.run_id,
reset_pipeline,
shutdown_monitor,
- job,
- schema,
- source,
- table,
resumable_source_manager,
+ models=models,
)
else:
pipeline = PipelineNonDLT(
@@ -475,11 +480,8 @@ async def _run(
job_inputs.run_id,
reset_pipeline,
shutdown_monitor,
- job,
- schema,
- source,
- table,
resumable_source_manager,
+ models=models,
)
result = await pipeline.run()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
index bb456cdcbf74..c250d02c6a8d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
@@ -109,7 +109,7 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:
# bare↔qualified tail matching would wrongly collapse them; match names exactly and seed
# per-repo location metadata on newly created rows.
is_github = source_type_enum == ExternalDataSourceType.GITHUB
- schemas_created, schemas_deleted = sync_old_schemas_with_new_schemas(
+ sync_result = sync_old_schemas_with_new_schemas(
schemas_to_sync,
source_id=inputs.source_id,
team_id=inputs.team_id,
@@ -119,16 +119,16 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:
else None,
)
- if len(schemas_created) > 0:
- logger.info(f"Added new schemas: {', '.join(schemas_created)}")
+ if len(sync_result.created) > 0:
+ logger.info(f"Added new schemas: {', '.join(sync_result.created)}")
- auto_enabled = auto_enable_new_schemas(source, schemas_created, {s.name: s for s in schemas})
+ auto_enabled = auto_enable_new_schemas(source, sync_result.created, {s.name: s for s in schemas})
if auto_enabled:
logger.info(f"Auto-enabled sync for new schemas: {', '.join(auto_enabled)}")
else:
logger.info("No new schemas to create")
- if len(schemas_deleted) > 0:
- logger.info(f"Deleted schemas: {', '.join(schemas_deleted)}")
+ if len(sync_result.deleted) > 0:
+ logger.info(f"Deleted schemas: {', '.join(sync_result.deleted)}")
else:
logger.info("No schemas to delete")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index e8c1127a3015..847738ea6ea7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (
AcquireV3LockActivityInputs,
CheckPipelineVersionActivityInputs,
+ HolderWorkflowDescription,
ReleaseV3LockActivityInputs,
acquire_v3_pipeline_lock_activity,
check_pipeline_version_activity,
@@ -177,7 +178,12 @@ class TestTakeOverStaleLock:
mock_acquire.assert_called_once_with(TEAM_ID, str(SCHEMA_ID), WORKFLOW_RUN_ID)
@patch(f"{MODULE}.get_v3_pipeline_lock_meta", return_value=None)
- @patch(f"{MODULE}._describe_holder_workflow", return_value=(WorkflowExecutionStatus.RUNNING, None, False))
+ @patch(
+ f"{MODULE}._describe_holder_workflow",
+ return_value=HolderWorkflowDescription(
+ status=WorkflowExecutionStatus.RUNNING, job=None, status_is_assumed=False
+ ),
+ )
@patch(f"{MODULE}.close_old_connections")
@patch(f"{MODULE}.get_v3_pipeline_lock_holder", return_value=HOLDER_TOKEN)
def test_fails_closed_when_holder_workflow_running(
@@ -186,7 +192,10 @@ class TestTakeOverStaleLock:
assert self._run() is False
@patch(f"{MODULE}.get_v3_pipeline_lock_meta", return_value=None)
- @patch(f"{MODULE}._describe_holder_workflow", return_value=(None, None, False))
+ @patch(
+ f"{MODULE}._describe_holder_workflow",
+ return_value=HolderWorkflowDescription(status=None, job=None, status_is_assumed=False),
+ )
@patch(f"{MODULE}.close_old_connections")
@patch(f"{MODULE}.get_v3_pipeline_lock_holder", return_value=HOLDER_TOKEN)
def test_fails_closed_when_describe_fails(
@@ -311,7 +320,9 @@ class TestTakeOverStaleLock:
holder_job.status = holder_status
with patch(
f"{MODULE}._describe_holder_workflow",
- return_value=(WorkflowExecutionStatus.COMPLETED, holder_job, False),
+ return_value=HolderWorkflowDescription(
+ status=WorkflowExecutionStatus.COMPLETED, job=holder_job, status_is_assumed=False
+ ),
):
assert self._run() is True
mock_release.assert_called_once_with(TEAM_ID, str(SCHEMA_ID), self.HOLDER_TOKEN)
@@ -331,7 +342,9 @@ class TestTakeOverStaleLock:
holder_job.status = "Running"
with patch(
f"{MODULE}._describe_holder_workflow",
- return_value=(WorkflowExecutionStatus.COMPLETED, holder_job, False),
+ return_value=HolderWorkflowDescription(
+ status=WorkflowExecutionStatus.COMPLETED, job=holder_job, status_is_assumed=False
+ ),
):
assert self._run() is False
mock_stale.assert_called_once()
diff --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.py
index d5cdc0e7765a..2ea979668d20 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
@@ -116,10 +116,10 @@ class TestGetModelsPrefetchesSource(BaseTest):
# Call the undecorated sync loader directly so the query capture runs on this thread.
# `.func` is the wrapped sync callable on database_sync_to_async_pool's DatabaseSyncToAsync
# (asgiref); it isn't on the decorator's static type, hence the cast.
- loaded_job, _, _, _ = cast(Any, module._get_models).func(str(job.id))
+ models = cast(Any, module._get_models).func(str(job.id))
with self.assertNumQueries(0):
- loaded_job.folder_path()
+ models.job.folder_path()
@pytest.mark.asyncio
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
index 9d4c1da93bcd..08c9d58bc0d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
@@ -5,6 +5,7 @@ from unittest import mock
from posthog.models.integration import UndecryptedIntegrationSecretError
+from products.warehouse_sources.backend.models.external_data_schema import SchemaSyncResult
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import sync_new_schemas as module
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.sync_new_schemas import (
SyncNewSchemasActivityInputs,
@@ -28,7 +29,9 @@ def _patch_common(source_mock, schemas_created=None, source_api_version=None):
"is_registered": mock.patch.object(module.SourceRegistry, "is_registered", return_value=True),
"get_source": mock.patch.object(module.SourceRegistry, "get_source", return_value=source_mock),
"sync_old_schemas_with_new_schemas": mock.patch.object(
- module, "sync_old_schemas_with_new_schemas", return_value=(schemas_created or [], [])
+ module,
+ "sync_old_schemas_with_new_schemas",
+ return_value=SchemaSyncResult(created=schemas_created or [], deleted=[]),
),
"auto_enable_new_schemas": mock.patch.object(module, "auto_enable_new_schemas", return_value=[]),
}
diff --git a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
index d862b213c751..e0d078fe68a1 100644
--- a/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
+++ b/products/warehouse_sources/backend/tests/test_schema_discovery_reconcile.py
@@ -84,7 +84,7 @@ class TestSchemaDiscoveryReconcile(BaseTest):
source = self._make_source()
existing = self._make_synced_schema(source, "public.users")
- created, _deleted = sync_old_schemas_with_new_schemas(
+ sync_result = sync_old_schemas_with_new_schemas(
{"public.users": None, "analytics.users": None},
source_id=str(source.pk),
team_id=self.team.pk,
@@ -92,7 +92,7 @@ class TestSchemaDiscoveryReconcile(BaseTest):
existing.refresh_from_db()
assert existing.should_sync is True
- assert "analytics.users" in created
+ assert "analytics.users" in sync_result.created
assert ExternalDataSchema.objects.filter(source_id=source.pk, name="analytics.users").exists()
def test_strict_match_creates_qualified_row_alongside_legacy_bare_row(self) -> None:
@@ -102,7 +102,7 @@ class TestSchemaDiscoveryReconcile(BaseTest):
source = self._make_source()
legacy = self._make_synced_schema(source, "issues")
- created, _deleted = sync_old_schemas_with_new_schemas(
+ sync_result = sync_old_schemas_with_new_schemas(
{"issues": None, "acme/other.issues": "acme/other · issues"},
source_id=str(source.pk),
team_id=self.team.pk,
@@ -114,7 +114,7 @@ class TestSchemaDiscoveryReconcile(BaseTest):
legacy.refresh_from_db()
assert legacy.should_sync is True
- assert created == ["acme/other.issues"]
+ assert sync_result.created == ["acme/other.issues"]
new_row = ExternalDataSchema.objects.get(source_id=source.pk, name="acme/other.issues")
assert new_row.sync_type_config.get("schema_metadata") == {
"source_repository": "acme/other",