:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse): retire duckgres batch sink (#76480)
Eric Duong1aaae413dc19
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 4821c3a29555..921f8f4f02ef 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -191,7 +191,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"DuckLakeBackfill","DuckLakeCatalog","DuckgresServer",- "DuckgresSinkSchemaState","EvaluationConfig","RemoteConfig","TeamConversationsSlackConfig",@@ -359,7 +358,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"SessionRecordingExternalReference", # via SessionRecording"SessionRecordingPlaylistItem", # via Playlist"SharePassword", # via SharingConfiguration- "SourceBatchDuckgresStatus", # via SourceBatch"SourceBatchStatus", # via SourceBatch"StreamlitAppSandbox", # via StreamlitApp"TaggedItem", # via Tag/Dashboard/Insightdiff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex f97f079207e1..295bc71b1f8f 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -1090,36 +1090,6 @@ jobs:"timestamp": "${{ github.event.head_commit.timestamp }}"}- - name: Check for changes that affect warehouse-sources-duckgres-load- id: check_changes_warehouse_sources_duckgres_load- run: |- if git diff --name-only HEAD^ HEAD | grep -qE '^products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/|^products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/|^products/warehouse_sources/backend/temporal/data_imports/pipelines/core/|^posthog/management/commands/run_warehouse_sources_duckgres_load\.py$|^posthog/warehouse/|^products/managed_warehouse/backend/|^products/data_warehouse/backend/|^products/warehouse_sources/backend/|^products/warehouse_sources_queue/backend/|^pyproject\.toml$|^Dockerfile$|^posthog/clickhouse/migrations/'; then- echo "changed=true" >> $GITHUB_OUTPUT- else- echo "changed=false" >> $GITHUB_OUTPUT- fi-- - name: Trigger Warehouse Sources Duckgres Load Cloud deployment- if: steps.check_changes_warehouse_sources_duckgres_load.outputs.changed == 'true'- uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1- with:- token: ${{ steps.deployer.outputs.token }}- repository: PostHog/charts- event-type: commit_state_update- client-payload: |- {- "values": {- "image": {- "sha": "${{ github.sha }}@${{ steps.image.outputs.digest }}"- }- },- "release": "warehouse-sources-duckgres-load",- "commit": ${{ toJson(github.event.head_commit) }},- "repository": ${{ toJson(github.repository) }},- "labels": ${{ steps.labels.outputs.labels }},- "timestamp": "${{ github.event.head_commit.timestamp }}"- }-- name: Trigger Data Warehouse CDP Producer Temporal Worker Cloud deploymentif: steps.check_changes_data_warehouse_temporal_worker.outputs.changed == 'true'uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex a166796e3a96..bc8c664b5fd5 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -294,8 +294,6 @@ rules:|SingleSessionSummary|SlackThreadTaskMapping|SourceBatch- |SourceBatchDuckgresApply- |SourceDuckgresGroupLease|SourceGroupLease|StreamlitApp|Subscription@@ -635,8 +633,6 @@ rules:|SingleSessionSummary|SlackThreadTaskMapping|SourceBatch- |SourceBatchDuckgresApply- |SourceDuckgresGroupLease|SourceGroupLease|StreamlitApp|Subscriptiondiff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 04f1cc70c75c..5390070bbb55 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -721,17 +721,6 @@ procs:tech: Python# no capability - manual start- warehouse-sources-duckgres-load:- shell: |-- bin/wait-for-docker && \- python manage.py run_warehouse_sources_duckgres_load --health-port 8092- autostart: false- ready_pattern: 'duckgres_batch_consumer_started'- groups:- layer: Tools- tech: Python- # no capability - manual start-# Grouping dimension the sidebar starts grouped by (press `g` to cycle/disable).default_group: layerdiff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.mdindex 0823101d75e4..f8d9b60691e2 100644--- a/posthog/dags/README_DUCKLINGS.md+++ b/posthog/dags/README_DUCKLINGS.md@@ -182,7 +182,7 @@ If multiple partitions for the same team run concurrently, they may race to crea- **Job definition**: `posthog/dags/events_backfill_to_duckling.py`- **Tests**: `posthog/dags/test_events_backfill_to_duckling.py`- **Dagster registration**: `posthog/dags/locations/data_stack.py`-- **DuckgresServer / DuckgresSinkSchemaState models**: `products/managed_warehouse/backend/models.py`+- **DuckgresServer model**: `products/managed_warehouse/backend/models.py`- **Control-plane team state**: `products/managed_warehouse/backend/cp_teams.py` and `products/managed_warehouse/backend/team_state.py`## S3 Path Structurediff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.pyindex 1438d6bb2ffd..e26319c9fb8c 100644--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py@@ -14,7 +14,7 @@ from asgiref.sync import sync_to_asynclogger = structlog.get_logger(__name__)-PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus", "sourcebatchduckgresstatus"]+PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus"]PARTITIONS_AHEAD = 7RETENTION_DAYS = 7@@ -26,13 +26,6 @@ RETENTION_STRANDED_ERROR = "batches aged out of retention without being processe# set in postgres_queue/jobs_db.py; 'pending' = never claimed)._NON_TERMINAL_BATCH_STATES = ("pending", "waiting", "waiting_retry", "executing")-# The duckgres apply-marker table is unpartitioned (small rows, UNIQUE-constrained),-# so retention is DELETE-based. Must comfortably exceed the consumers' eligibility-# window (PARTITION_PRUNING_INTERVAL, 14d): the duckgres ordering gate and-# has_applied idempotency read apply rows for everything still eligible.-DUCKGRES_APPLY_TABLE = "sourcebatchduckgresapply"-DUCKGRES_APPLY_RETENTION_DAYS = 30-@dataclass(frozen=True, slots=True)class PartitionResult:@@ -112,17 +105,6 @@ async def manage_warehouse_sources_queue_partitions() -> dict:_verify_partitions(conn, today, errors)- try:- cursor = conn.execute(- f"DELETE FROM {DUCKGRES_APPLY_TABLE} "- f"WHERE created_at < now() - interval '{DUCKGRES_APPLY_RETENTION_DAYS} days'"- )- if cursor.rowcount:- logger.info("duckgres_apply_markers_pruned", count=cursor.rowcount)- except Exception as e:- errors.append(f"Failed to prune {DUCKGRES_APPLY_TABLE}: {e}")- logger.exception("Failed to prune duckgres apply markers")-s3_deleted = _cleanup_old_s3_extractions(today, errors)result = PartitionResult(ensured=ensured, dropped=dropped, errors=errors, s3_deleted=s3_deleted)diff --git a/products/managed_warehouse/backend/facade/api.py b/products/managed_warehouse/backend/facade/api.pyindex f2b806d5a5c6..d7ca4ee0ceaa 100644--- a/products/managed_warehouse/backend/facade/api.py+++ b/products/managed_warehouse/backend/facade/api.py@@ -8,7 +8,6 @@ commands. Django models remain implementation details of the product.from __future__ import annotations-from collections.abc import Iterablefrom datetime import datefrom typing import TYPE_CHECKINGfrom uuid import UUID@@ -59,7 +58,6 @@ __all__ = ["reconcile_stored_bucket_config","resolve_team_earliest_event_date","setup_duckgres_session",- "sink_concurrency_by_trusted_organization_ids","update_team_earliest_event_date","validate_schema_name",]@@ -90,7 +88,6 @@ def _to_stored_server_config(server: DuckgresServer) -> DuckgresStoredServerConf),catalog=catalog,bucket=bucket,- sink_max_concurrency=server.sink_max_concurrency,)@@ -185,22 +182,6 @@ def reconcile_stored_bucket_config(organization_id: str | UUID, *, bucket: str,)-def sink_concurrency_by_trusted_organization_ids(- trusted_organization_ids: Iterable[str],-) -> dict[str, int]:- from products.managed_warehouse.backend.models import DuckgresServer # noqa: PLC0415-- organization_ids = tuple(trusted_organization_ids)- if not organization_ids:- return {}- return {- str(organization_id): sink_max_concurrency- for organization_id, sink_max_concurrency in DuckgresServer.objects.filter(- organization_id__in=organization_ids- ).values_list("organization_id", "sink_max_concurrency")- }--def get_control_plane_bucket(organization_id: str | UUID) -> str | None:from products.managed_warehouse.backend.presentation.views import cp_bucket_for # noqa: PLC0415diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex 413e50ab76e8..ad481c1b936b 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -21,12 +21,6 @@ from uuid import UUID__all__ = ["CPUnavailableError","DuckgresQueryServerConfig",- "DuckgresSinkBackfillPlanInput",- "DuckgresSinkBackfillRunReference",- "DuckgresSinkState",- "DuckgresSinkStateCreateInput",- "DuckgresSinkStateGaugeStats",- "DuckgresSinkStateRecord","DuckgresStoredBucketConfig","DuckgresStoredServerConfig","DuckLakeCatalogConnectionConfig",@@ -93,7 +87,6 @@ class DuckgresStoredServerConfig:query_server: DuckgresQueryServerConfigcatalog: DuckLakeCatalogConnectionConfig | Nonebucket: DuckgresStoredBucketConfig | None- sink_max_concurrency: int@dataclass(frozen=True, kw_only=True)@@ -191,65 +184,3 @@ class DuckLakeTableResult:row_count: intfile_size_bytes: int = 0file_size_delta_bytes: int = 0---class DuckgresSinkState(StrEnum):- PENDING_BACKFILL = "pending_backfill"- BACKFILLING = "backfilling"- PRIMED = "primed"- NEEDS_RESYNC = "needs_resync"---@dataclass(frozen=True, kw_only=True)-class DuckgresSinkStateCreateInput:- team_id: int- schema_id: UUID- state: DuckgresSinkState = DuckgresSinkState.PENDING_BACKFILL- snapshot_version: int | None = None- plan_cutoff: datetime | None = None- backfill_run_uuid: str | None = None- chunk_count: int | None = None- chunks_applied: int = 0- last_error: str | None = None- consecutive_failures: int = 0- first_failed_at: datetime | None = None- queue_last_applied_at: datetime | None = None---@dataclass(frozen=True, kw_only=True)-class DuckgresSinkBackfillPlanInput:- snapshot_version: int- backfill_run_uuid: str- chunk_count: int---@dataclass(frozen=True, kw_only=True)-class DuckgresSinkBackfillRunReference:- schema_id: UUID- backfill_run_uuid: str | None---@dataclass(frozen=True, kw_only=True)-class DuckgresSinkStateRecord:- id: UUID- team_id: int- schema_id: UUID- state: DuckgresSinkState- snapshot_version: int | None = None- plan_cutoff: datetime | None = None- backfill_run_uuid: str | None = None- chunk_count: int | None = None- chunks_applied: int = 0- last_error: str | None = None- consecutive_failures: int = 0- first_failed_at: datetime | None = None- queue_last_applied_at: datetime | None = None- updated_at: datetime | None = None- organization_id: UUID | None = None---@dataclass(frozen=True, kw_only=True)-class DuckgresSinkStateGaugeStats:- counts: dict[DuckgresSinkState, int]- failing_count: int- oldest_failure_at: datetime | Nonediff --git a/products/managed_warehouse/backend/facade/sink_state.py b/products/managed_warehouse/backend/facade/sink_state.pydeleted file mode 100644index 0be6afeec650..000000000000--- a/products/managed_warehouse/backend/facade/sink_state.py+++ /dev/null@@ -1,226 +0,0 @@-from __future__ import annotations--from collections.abc import Iterable-from typing import TYPE_CHECKING, TypeVar-from uuid import UUID--from django.db.models import Model--from products.managed_warehouse.backend import sink_state-from products.managed_warehouse.backend.facade.contracts import (- DuckgresSinkBackfillPlanInput,- DuckgresSinkBackfillRunReference,- DuckgresSinkStateCreateInput,- DuckgresSinkStateGaugeStats,- DuckgresSinkStateRecord,-)--if TYPE_CHECKING:- from django.db.models import QuerySet---ModelT = TypeVar("ModelT", bound=Model)--__all__ = [- "bulk_create_sink_states",- "claim_backfill_plan",- "claim_pending_backfill",- "delete_sink_state",- "exclude_schemas_with_sink_state",- "get_sink_state",- "get_sink_state_gauge_stats",- "is_backfill_capacity_reached",- "list_failing_schema_ids",- "list_needs_resync_sink_states",- "list_pending_sink_states",- "list_primed_schema_ids",- "list_reconciling_backfill_states",- "list_sink_backfill_run_references",- "list_sink_states_for_team",- "mark_backfill_completed",- "mark_backfill_superseded",- "mark_backfill_unsupported",- "mark_empty_backfill_primed",- "mark_resync_completed",- "mark_sink_state_diverged",- "mark_sink_state_primed",- "record_backfill_progress",- "record_live_batch_applied",- "record_terminal_backfill_failure",- "reset_backfill_plan",- "reset_stale_backfill_claims",- "return_backfill_claim_to_pending",-]---def bulk_create_sink_states(inputs: Iterable[DuckgresSinkStateCreateInput]) -> None:- sink_state.bulk_create_sink_states(inputs)---def get_sink_state(schema_id: str | UUID) -> DuckgresSinkStateRecord | None:- return sink_state.get_sink_state(schema_id)---def list_sink_backfill_run_references(team_ids: list[int] | None) -> list[DuckgresSinkBackfillRunReference]:- return sink_state.list_sink_backfill_run_references(team_ids)---def list_sink_states_for_team(team_id: int) -> list[DuckgresSinkStateRecord]:- return sink_state.list_sink_states_for_team(team_id)---def list_primed_schema_ids(team_ids: list[int] | None) -> list[str]:- return sink_state.list_primed_schema_ids(team_ids)---def list_failing_schema_ids(team_ids: list[int] | None, *, failing_threshold: int) -> list[str]:- return sink_state.list_failing_schema_ids(team_ids, failing_threshold=failing_threshold)---def exclude_schemas_with_sink_state(- schemas: QuerySet[ModelT],-) -> QuerySet[ModelT]:- """Keep the ExternalDataSchema anti-join in SQL while state ownership stays private."""- return sink_state.exclude_schemas_with_sink_state(schemas)---def list_pending_sink_states(team_ids: list[int] | None, *, limit: int) -> list[DuckgresSinkStateRecord]:- return sink_state.list_pending_sink_states(team_ids, limit=limit)---def is_backfill_capacity_reached(- max_concurrent_backfills: int,- *,- organization_id: UUID | None = None,- exclude_id: UUID | None = None,-) -> bool:- return sink_state.is_backfill_capacity_reached(- max_concurrent_backfills,- organization_id=organization_id,- exclude_id=exclude_id,- )---def claim_pending_backfill(state_id: UUID) -> bool:- return sink_state.claim_pending_backfill(state_id)---def return_backfill_claim_to_pending(- state_id: UUID,- *,- error: str | None = None,- record_failure: bool = False,-) -> None:- sink_state.return_backfill_claim_to_pending(state_id, error=error, record_failure=record_failure)---def mark_backfill_unsupported(state_id: UUID, *, error: str) -> None:- sink_state.mark_backfill_unsupported(state_id, error=error)---def mark_sink_state_primed(- schema_id: str | UUID,- *,- backfill_run_uuid: str,- chunks_applied: int | None = None,-) -> bool:- return sink_state.mark_sink_state_primed(- schema_id,- backfill_run_uuid=backfill_run_uuid,- chunks_applied=chunks_applied,- )---def mark_sink_state_diverged(- schema_id: str | UUID,- *,- run_uuid: str,- error: str,- failing_threshold: int,-) -> bool:- return sink_state.mark_sink_state_diverged(- schema_id,- run_uuid=run_uuid,- error=error,- failing_threshold=failing_threshold,- )---def reset_backfill_plan(state_id: UUID) -> None:- sink_state.reset_backfill_plan(state_id)---def mark_empty_backfill_primed(state_id: UUID) -> None:- sink_state.mark_empty_backfill_primed(state_id)---def claim_backfill_plan(state_id: UUID, input: DuckgresSinkBackfillPlanInput) -> bool:- return sink_state.claim_backfill_plan(state_id, input)---def delete_sink_state(schema_id: UUID) -> None:- sink_state.delete_sink_state(schema_id)---def reset_stale_backfill_claims(team_ids: list[int] | None, *, lease_seconds: int) -> int:- return sink_state.reset_stale_backfill_claims(team_ids, lease_seconds=lease_seconds)---def list_reconciling_backfill_states(team_ids: list[int] | None) -> list[DuckgresSinkStateRecord]:- return sink_state.list_reconciling_backfill_states(team_ids)---def list_needs_resync_sink_states(team_ids: list[int] | None) -> list[DuckgresSinkStateRecord]:- return sink_state.list_needs_resync_sink_states(team_ids)---def mark_backfill_completed(state_id: UUID, *, backfill_run_uuid: str, chunks_applied: int) -> bool:- return sink_state.mark_backfill_completed(- state_id,- backfill_run_uuid=backfill_run_uuid,- chunks_applied=chunks_applied,- )---def mark_backfill_superseded(state_id: UUID) -> bool:- return sink_state.mark_backfill_superseded(state_id)---def record_terminal_backfill_failure(- state_id: UUID,- *,- error: str,- chunks_applied: int,- failing_threshold: int,-) -> None:- sink_state.record_terminal_backfill_failure(- state_id,- error=error,- chunks_applied=chunks_applied,- failing_threshold=failing_threshold,- )---def record_backfill_progress(- state_id: UUID,- *,- chunks_applied: int,- reset_failure_streak: bool,-) -> None:- sink_state.record_backfill_progress(- state_id,- chunks_applied=chunks_applied,- reset_failure_streak=reset_failure_streak,- )---def mark_resync_completed(state_id: UUID) -> bool:- return sink_state.mark_resync_completed(state_id)---def get_sink_state_gauge_stats(*, failing_threshold: int) -> DuckgresSinkStateGaugeStats:- return sink_state.get_sink_state_gauge_stats(failing_threshold=failing_threshold)---def record_live_batch_applied(schema_id: str | UUID) -> None:- sink_state.record_live_batch_applied(schema_id)diff --git a/products/managed_warehouse/backend/facade/testing.py b/products/managed_warehouse/backend/facade/testing.pyindex 666c66193f13..0bc0466853db 100644--- a/products/managed_warehouse/backend/facade/testing.py+++ b/products/managed_warehouse/backend/facade/testing.py@@ -1,47 +1,9 @@from __future__ import annotations-from uuid import UUID+from products.managed_warehouse.backend import source_job_state+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseSourceJobUpdate-from products.managed_warehouse.backend import sink_state, source_job_state-from products.managed_warehouse.backend.facade.contracts import (- DuckgresSinkStateCreateInput,- DuckgresSinkStateRecord,- ManagedWarehouseSourceJobUpdate,-)--__all__ = [- "count_sink_states",- "create_sink_state",- "get_sink_state",- "list_sink_states",- "replace_sink_state",- "record_source_job_state",- "sink_state_exists",-]---def create_sink_state(input: DuckgresSinkStateCreateInput) -> DuckgresSinkStateRecord:- return sink_state.create_sink_state(input)---def get_sink_state(state_id: UUID) -> DuckgresSinkStateRecord | None:- return sink_state.get_sink_state_by_id(state_id)---def list_sink_states() -> list[DuckgresSinkStateRecord]:- return sink_state.list_sink_states_for_test()---def replace_sink_state(record: DuckgresSinkStateRecord) -> None:- sink_state.replace_sink_state_for_test(record)---def count_sink_states() -> int:- return sink_state.count_sink_states_for_test()---def sink_state_exists(state_id: UUID) -> bool:- return sink_state.sink_state_exists_for_test(state_id)+__all__ = ["record_source_job_state"]def record_source_job_state(input: ManagedWarehouseSourceJobUpdate) -> None:diff --git a/products/managed_warehouse/backend/migrations/0003_remove_duckgres_batch_sink_state.py b/products/managed_warehouse/backend/migrations/0003_remove_duckgres_batch_sink_state.pynew file mode 100644index 000000000000..7145bbfce923--- /dev/null+++ b/products/managed_warehouse/backend/migrations/0003_remove_duckgres_batch_sink_state.py@@ -0,0 +1,27 @@+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("managed_warehouse", "0002_managedwarehousesourcejob"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="duckgresserver",+ name="sink_max_concurrency",+ ),+ migrations.DeleteModel(+ name="DuckgresSinkSchemaState",+ ),+ ],+ database_operations=[+ migrations.RunSQL(+ sql="ALTER TABLE posthog_duckgresserver ALTER COLUMN sink_max_concurrency SET DEFAULT 4;",+ reverse_sql="ALTER TABLE posthog_duckgresserver ALTER COLUMN sink_max_concurrency DROP DEFAULT;",+ ),+ ],+ ),+ ]diff --git a/products/managed_warehouse/backend/migrations/max_migration.txt b/products/managed_warehouse/backend/migrations/max_migration.txtindex c5d821bc255a..ee613f55db27 100644--- a/products/managed_warehouse/backend/migrations/max_migration.txt+++ b/products/managed_warehouse/backend/migrations/max_migration.txt@@ -1 +1 @@-0002_managedwarehousesourcejob+0003_remove_duckgres_batch_sink_statediff --git a/products/managed_warehouse/backend/models.py b/products/managed_warehouse/backend/models.pyindex e2fb3b3e3575..f2a8c62d437b 100644--- a/products/managed_warehouse/backend/models.py+++ b/products/managed_warehouse/backend/models.py@@ -48,11 +48,6 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):# Region travels with the bucket: set alongside it, left NULL when no bucket is# recorded yet (status_for()'s self-heal fills both in once the control plane reports them).bucket_region = models.CharField(max_length=50, null=True, blank=True, default=None)- # Fleet-wide cap on the batch sink's concurrently processing groups for this- # org — each in-flight group holds at most one connection to the org's- # duckgres server, so this bounds the sink's connection footprint no matter- # how many consumer pods run. Soft cap: enforced at group-claim time.- sink_max_concurrency = models.IntegerField(default=4)class Meta:db_table = "posthog_duckgresserver"@@ -73,80 +68,6 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):}-class DuckgresSinkSchemaState(CreatedMetaFields, UpdatedMetaFields, UUIDModel):- r"""Per-schema lifecycle of the Duckgres v3 batch sink.-- The sink only applies live batches for a schema once its history has been- primed into duckgres (or it needs no priming). The backfill planner owns- the transitions:-- PENDING_BACKFILL -> BACKFILLING -> PRIMED- \-> (superseded by a live full refresh) -> PRIMED- PRIMED -> NEEDS_RESYNC (retention-loss gap) -> PENDING_BACKFILL- """-- class State(models.TextChoices):- PENDING_BACKFILL = "pending_backfill", "Pending backfill"- BACKFILLING = "backfilling", "Backfilling"- PRIMED = "primed", "Primed"- NEEDS_RESYNC = "needs_resync", "Needs resync"-- # db_constraint=False: a real FK constraint on posthog_team locks that hot- # table when this table is created (HotTableAlterPolicy). The tenant link is- # enforced at the app level.- team = models.ForeignKey(- "posthog.Team",- on_delete=models.CASCADE,- related_name="duckgres_sink_schema_states",- db_constraint=False,- )- # ExternalDataSchema id. Not a FK: the queue addresses schemas by string id- # and the schema row may be soft-deleted while sink state must survive for- # cleanup decisions.- schema_id = models.UUIDField(unique=True)- state = models.CharField(max_length=32, choices=State.choices, default=State.PENDING_BACKFILL)- # Delta table version the backfill is pinned to.- snapshot_version = models.BigIntegerField(null=True, blank=True)- # Deprecated planning boundary retained for rows created by older planner- # revisions. New plans derive containment from Delta commit versions.- plan_cutoff = models.DateTimeField(null=True, blank=True)- backfill_run_uuid = models.CharField(max_length=200, null=True, blank=True)- chunk_count = models.IntegerField(null=True, blank=True)- chunks_applied = models.IntegerField(default=0)- last_error = models.TextField(null=True, blank=True)- # Failure streak since the last forward progress. Drives planner retry- # backoff and the failing-schema classification that splits these schemas'- # backlog out of the pageable blocked gauges. Reset on any progress.- consecutive_failures = models.IntegerField(default=0)- # When the current failure streak began — the durable "backfill owed since"- # anchor. Unlike batch-derived gauges it survives queue retention.- first_failed_at = models.DateTimeField(null=True, blank=True)- # Override CreatedMetaFields.created_by to drop the DB-level FK: a real- # constraint on posthog_user takes a lock on that hot table when this table- # is created (HotTableAlterPolicy). App-level enforcement is enough for an- # optional audit pointer.- created_by = models.ForeignKey(- "posthog.User",- on_delete=models.SET_NULL,- null=True,- blank=True,- db_constraint=False,- )-- # When the sink last applied a live (non-backfill) imported batch to duckgres for this- # schema, stamped by the sink at apply time. The web tier reads it from the main DB so- # the Data ops UI can report import activity without querying the warehouse-sources- # queue DB (which it has no access to). NULL = no live apply recorded since this field- # shipped. It's an event timestamp, not a liveness signal — history, never "stale".- queue_last_applied_at = models.DateTimeField(null=True, blank=True)-- class Meta:- db_table = "posthog_duckgressinkschemastate"- verbose_name = "Duckgres sink schema state"- verbose_name_plural = "Duckgres sink schema states"- indexes = [models.Index(fields=["team", "state"], name="duckgres_sink_team_state_idx")]--class ManagedWarehouseSourceJob(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):class WorkflowType(models.TextChoices):COPY = "copy", "Copy"diff --git a/products/managed_warehouse/backend/sink_state.py b/products/managed_warehouse/backend/sink_state.pydeleted file mode 100644index e346b6aa4aa6..000000000000--- a/products/managed_warehouse/backend/sink_state.py+++ /dev/null@@ -1,453 +0,0 @@-from __future__ import annotations--from collections.abc import Iterable-from datetime import timedelta-from typing import TYPE_CHECKING, TypeVar-from uuid import UUID--from django.db.models import Count, F, Min, Model, Q, Value-from django.db.models.functions import Coalesce, Greatest-from django.utils import timezone--from products.managed_warehouse.backend.facade.contracts import (- DuckgresSinkBackfillPlanInput,- DuckgresSinkBackfillRunReference,- DuckgresSinkState,- DuckgresSinkStateCreateInput,- DuckgresSinkStateGaugeStats,- DuckgresSinkStateRecord,-)-from products.managed_warehouse.backend.models import DuckgresSinkSchemaState--if TYPE_CHECKING:- from django.db.models import QuerySet---ModelT = TypeVar("ModelT", bound=Model)---def _to_record(- state: DuckgresSinkSchemaState,- *,- organization_id: UUID | None = None,-) -> DuckgresSinkStateRecord:- return DuckgresSinkStateRecord(- id=state.id,- team_id=state.team_id,- schema_id=state.schema_id,- state=DuckgresSinkState(state.state),- snapshot_version=state.snapshot_version,- plan_cutoff=state.plan_cutoff,- backfill_run_uuid=state.backfill_run_uuid,- chunk_count=state.chunk_count,- chunks_applied=state.chunks_applied,- last_error=state.last_error,- consecutive_failures=state.consecutive_failures,- first_failed_at=state.first_failed_at,- queue_last_applied_at=state.queue_last_applied_at,- updated_at=state.updated_at,- organization_id=organization_id,- )---def _create_model(input: DuckgresSinkStateCreateInput) -> DuckgresSinkSchemaState:- return DuckgresSinkSchemaState(- team_id=input.team_id,- schema_id=input.schema_id,- state=input.state.value,- snapshot_version=input.snapshot_version,- plan_cutoff=input.plan_cutoff,- backfill_run_uuid=input.backfill_run_uuid,- chunk_count=input.chunk_count,- chunks_applied=input.chunks_applied,- last_error=input.last_error,- consecutive_failures=input.consecutive_failures,- first_failed_at=input.first_failed_at,- queue_last_applied_at=input.queue_last_applied_at,- )---def create_sink_state(input: DuckgresSinkStateCreateInput) -> DuckgresSinkStateRecord:- state = _create_model(input)- state.save(force_insert=True)- return _to_record(state)---def bulk_create_sink_states(inputs: Iterable[DuckgresSinkStateCreateInput]) -> None:- DuckgresSinkSchemaState.objects.bulk_create((_create_model(input) for input in inputs), ignore_conflicts=True)---def get_sink_state(schema_id: str | UUID) -> DuckgresSinkStateRecord | None:- try:- return _to_record(DuckgresSinkSchemaState.objects.get(schema_id=schema_id))- except DuckgresSinkSchemaState.DoesNotExist:- return None---def get_sink_state_by_id(state_id: UUID) -> DuckgresSinkStateRecord | None:- try:- return _to_record(DuckgresSinkSchemaState.objects.get(id=state_id))- except DuckgresSinkSchemaState.DoesNotExist:- return None---def list_sink_states_for_team(team_id: int) -> list[DuckgresSinkStateRecord]:- return [- _to_record(state) for state in DuckgresSinkSchemaState.objects.filter(team_id=team_id).order_by("schema_id")- ]---def list_sink_backfill_run_references(team_ids: list[int] | None) -> list[DuckgresSinkBackfillRunReference]:- states = DuckgresSinkSchemaState.objects.all()- if team_ids is not None:- states = states.filter(team_id__in=team_ids)- return [- DuckgresSinkBackfillRunReference(schema_id=schema_id, backfill_run_uuid=backfill_run_uuid)- for schema_id, backfill_run_uuid in states.values_list("schema_id", "backfill_run_uuid")- ]---def list_primed_schema_ids(team_ids: list[int] | None) -> list[str]:- states = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkState.PRIMED.value)- if team_ids is not None:- states = states.filter(team_id__in=team_ids)- return [str(schema_id) for schema_id in states.values_list("schema_id", flat=True)]---def _failing_q(failing_threshold: int) -> Q:- return Q(consecutive_failures__gte=failing_threshold) | Q(state=DuckgresSinkState.NEEDS_RESYNC.value)---def list_failing_schema_ids(team_ids: list[int] | None, *, failing_threshold: int) -> list[str]:- states = DuckgresSinkSchemaState.objects.exclude(state=DuckgresSinkState.PRIMED.value).filter(- _failing_q(failing_threshold)- )- if team_ids is not None:- states = states.filter(team_id__in=team_ids)- return [str(schema_id) for schema_id in states.values_list("schema_id", flat=True)]---def exclude_schemas_with_sink_state(- schemas: QuerySet[ModelT],-) -> QuerySet[ModelT]:- return schemas.exclude(id__in=DuckgresSinkSchemaState.objects.values("schema_id"))---def list_pending_sink_states(team_ids: list[int] | None, *, limit: int) -> list[DuckgresSinkStateRecord]:- states = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkState.PENDING_BACKFILL.value)- if team_ids is not None:- states = states.filter(team_id__in=team_ids)- return [- _to_record(state, organization_id=state.team.organization_id)- for state in states.select_related("team").order_by("updated_at")[:limit]- ]---def is_backfill_capacity_reached(- max_concurrent_backfills: int,- *,- organization_id: UUID | None = None,- exclude_id: UUID | None = None,-) -> bool:- states = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkState.BACKFILLING.value)- if organization_id is not None:- states = states.filter(team__organization_id=organization_id)- if exclude_id is not None:- states = states.exclude(id=exclude_id)- return states.count() >= max_concurrent_backfills---def claim_pending_backfill(state_id: UUID) -> bool:- return bool(- DuckgresSinkSchemaState.objects.filter(- id=state_id,- state=DuckgresSinkState.PENDING_BACKFILL.value,- ).update(- state=DuckgresSinkState.BACKFILLING.value,- updated_at=timezone.now(),- )- )---def return_backfill_claim_to_pending(- state_id: UUID,- *,- error: str | None = None,- record_failure: bool = False,-) -> None:- now = timezone.now()- updates: dict[str, object] = {- "state": DuckgresSinkState.PENDING_BACKFILL.value,- "updated_at": now,- }- if error is not None:- updates["last_error"] = error- if record_failure:- updates.update(- consecutive_failures=F("consecutive_failures") + 1,- first_failed_at=Coalesce(F("first_failed_at"), Value(now)),- )- DuckgresSinkSchemaState.objects.filter(- id=state_id,- state=DuckgresSinkState.BACKFILLING.value,- backfill_run_uuid__isnull=True,- ).update(**updates)---def mark_backfill_unsupported(state_id: UUID, *, error: str) -> None:- now = timezone.now()- DuckgresSinkSchemaState.objects.filter(id=state_id).update(- state=DuckgresSinkState.NEEDS_RESYNC.value,- last_error=error[:2000],- updated_at=now,- consecutive_failures=F("consecutive_failures") + 1,- first_failed_at=Coalesce(F("first_failed_at"), Value(now)),- )---def mark_sink_state_primed(- schema_id: str | UUID,- *,- backfill_run_uuid: str,- chunks_applied: int | None = None,-) -> bool:- updates: dict[str, object] = {- "state": DuckgresSinkState.PRIMED.value,- "last_error": None,- "updated_at": timezone.now(),- "consecutive_failures": 0,- "first_failed_at": None,- }- if chunks_applied is not None:- updates["chunks_applied"] = chunks_applied- return bool(- DuckgresSinkSchemaState.objects.filter(- schema_id=schema_id,- state=DuckgresSinkState.BACKFILLING.value,- backfill_run_uuid=backfill_run_uuid,- ).update(**updates)- )---def mark_sink_state_diverged(- schema_id: str | UUID,- *,- run_uuid: str,- error: str,- failing_threshold: int,-) -> bool:- now = timezone.now()- return bool(- DuckgresSinkSchemaState.objects.filter(- schema_id=schema_id,- state=DuckgresSinkState.PRIMED.value,- ).update(- state=DuckgresSinkState.NEEDS_RESYNC.value,- last_error=f"live run {run_uuid} failed in the duckgres sink: {error}"[:2000],- updated_at=now,- consecutive_failures=Greatest(F("consecutive_failures"), Value(failing_threshold)),- first_failed_at=Coalesce(F("first_failed_at"), Value(now)),- )- )---def reset_backfill_plan(state_id: UUID) -> None:- # Operator fresh start: the streak (and its backoff) must not outlive the run it was recorded against.- DuckgresSinkSchemaState.objects.filter(id=state_id).update(- state=DuckgresSinkState.PENDING_BACKFILL.value,- snapshot_version=None,- plan_cutoff=None,- backfill_run_uuid=None,- chunk_count=None,- chunks_applied=0,- last_error=None,- updated_at=timezone.now(),- consecutive_failures=0,- first_failed_at=None,- )---def mark_empty_backfill_primed(state_id: UUID) -> None:- DuckgresSinkSchemaState.objects.filter(id=state_id).update(- state=DuckgresSinkState.PRIMED.value,- last_error=None,- updated_at=timezone.now(),- consecutive_failures=0,- first_failed_at=None,- )---def claim_backfill_plan(state_id: UUID, input: DuckgresSinkBackfillPlanInput) -> bool:- return bool(- DuckgresSinkSchemaState.objects.filter(- id=state_id,- state=DuckgresSinkState.BACKFILLING.value,- backfill_run_uuid__isnull=True,- ).update(- snapshot_version=input.snapshot_version,- plan_cutoff=None,- backfill_run_uuid=input.backfill_run_uuid,- chunk_count=input.chunk_count,- chunks_applied=0,- last_error=None,- updated_at=timezone.now(),- consecutive_failures=0,- first_failed_at=None,- )- )---def delete_sink_state(schema_id: UUID) -> None:- DuckgresSinkSchemaState.objects.filter(schema_id=schema_id).delete()---def reset_stale_backfill_claims(team_ids: list[int] | None, *, lease_seconds: int) -> int:- stale = DuckgresSinkSchemaState.objects.filter(- state=DuckgresSinkState.BACKFILLING.value,- backfill_run_uuid__isnull=True,- updated_at__lt=timezone.now() - timedelta(seconds=lease_seconds),- )- if team_ids is not None:- stale = stale.filter(team_id__in=team_ids)- return stale.update(state=DuckgresSinkState.PENDING_BACKFILL.value, updated_at=timezone.now())---def list_reconciling_backfill_states(team_ids: list[int] | None) -> list[DuckgresSinkStateRecord]:- states = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkState.BACKFILLING.value)- if team_ids is not None:- states = states.filter(team_id__in=team_ids)- return [_to_record(state) for state in states if state.backfill_run_uuid]---def list_needs_resync_sink_states(team_ids: list[int] | None) -> list[DuckgresSinkStateRecord]:- states = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkState.NEEDS_RESYNC.value)- if team_ids is not None:- states = states.filter(team_id__in=team_ids)- return [_to_record(state) for state in states]---def mark_backfill_completed(state_id: UUID, *, backfill_run_uuid: str, chunks_applied: int) -> bool:- return bool(- DuckgresSinkSchemaState.objects.filter(- id=state_id,- state=DuckgresSinkState.BACKFILLING.value,- backfill_run_uuid=backfill_run_uuid,- ).update(- state=DuckgresSinkState.PRIMED.value,- chunks_applied=chunks_applied,- last_error=None,- updated_at=timezone.now(),- consecutive_failures=0,- first_failed_at=None,- )- )---def mark_backfill_superseded(state_id: UUID) -> bool:- return bool(- DuckgresSinkSchemaState.objects.filter(- id=state_id,- state=DuckgresSinkState.BACKFILLING.value,- ).update(- state=DuckgresSinkState.NEEDS_RESYNC.value,- last_error=None,- updated_at=timezone.now(),- )- )---def record_terminal_backfill_failure(- state_id: UUID,- *,- error: str,- chunks_applied: int,- failing_threshold: int,-) -> None:- now = timezone.now()- DuckgresSinkSchemaState.objects.filter(id=state_id).update(- last_error=error[:2000],- chunks_applied=chunks_applied,- consecutive_failures=Greatest(F("consecutive_failures"), Value(failing_threshold)),- first_failed_at=Coalesce(F("first_failed_at"), Value(now)),- updated_at=now,- )---def record_backfill_progress(- state_id: UUID,- *,- chunks_applied: int,- reset_failure_streak: bool,-) -> None:- updates: dict[str, object] = {- "chunks_applied": chunks_applied,- "updated_at": timezone.now(),- }- if reset_failure_streak:- updates.update(consecutive_failures=0, first_failed_at=None)- DuckgresSinkSchemaState.objects.filter(id=state_id).update(**updates)---def mark_resync_completed(state_id: UUID) -> bool:- return bool(- DuckgresSinkSchemaState.objects.filter(- id=state_id,- state=DuckgresSinkState.NEEDS_RESYNC.value,- ).update(- state=DuckgresSinkState.PRIMED.value,- last_error=None,- updated_at=timezone.now(),- consecutive_failures=0,- first_failed_at=None,- )- )---def get_sink_state_gauge_stats(*, failing_threshold: int) -> DuckgresSinkStateGaugeStats:- counts = {- DuckgresSinkState(state): count- for state, count in DuckgresSinkSchemaState.objects.values_list("state").annotate(n=Count("id"))- }- failing = DuckgresSinkSchemaState.objects.exclude(state=DuckgresSinkState.PRIMED.value).filter(- _failing_q(failing_threshold)- )- stats = failing.aggregate(n=Count("id"), oldest=Min("first_failed_at"))- return DuckgresSinkStateGaugeStats(- counts=counts,- failing_count=stats["n"] or 0,- oldest_failure_at=stats["oldest"],- )---def record_live_batch_applied(schema_id: str | UUID) -> None:- DuckgresSinkSchemaState.objects.filter(schema_id=schema_id).update(queue_last_applied_at=timezone.now())---def replace_sink_state_for_test(record: DuckgresSinkStateRecord) -> None:- DuckgresSinkSchemaState.objects.filter(id=record.id).update(- team_id=record.team_id,- schema_id=record.schema_id,- state=record.state.value,- snapshot_version=record.snapshot_version,- plan_cutoff=record.plan_cutoff,- backfill_run_uuid=record.backfill_run_uuid,- chunk_count=record.chunk_count,- chunks_applied=record.chunks_applied,- last_error=record.last_error,- consecutive_failures=record.consecutive_failures,- first_failed_at=record.first_failed_at,- queue_last_applied_at=record.queue_last_applied_at,- updated_at=record.updated_at,- )---def list_sink_states_for_test() -> list[DuckgresSinkStateRecord]:- return [_to_record(state) for state in DuckgresSinkSchemaState.objects.all()]---def count_sink_states_for_test() -> int:- return DuckgresSinkSchemaState.objects.count()---def sink_state_exists_for_test(state_id: UUID) -> bool:- return DuckgresSinkSchemaState.objects.filter(id=state_id).exists()diff --git a/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.pyindex 544d4a4a9d45..edb4c03bde04 100644--- a/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py+++ b/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py@@ -73,7 +73,6 @@ from products.managed_warehouse.backend.temporal.metrics import ()from products.managed_warehouse.backend.temporal.source_job_state import record_managed_warehouse_source_job_activityfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema-from products.warehouse_sources.backend.facade.pipelines import DUCKGRES_BATCH_SINK_FLAG, is_duckgres_sink_team_memberLOGGER = get_logger(__name__)DATA_IMPORTS_DUCKLAKE_WORKFLOW_PREFIX = "data_imports"@@ -288,13 +287,7 @@ class DuckLakeCopyDataImportsVerificationResult:@activity.defnasync def ducklake_copy_data_imports_gate_activity(inputs: DuckLakeCopyWorkflowGateInputs) -> bool:- """Evaluate whether the DuckLake data imports copy workflow should run for a team.-- The mutual exclusion with the Duckgres v3 batch sink is per-source and lives in- prepare_data_imports_ducklake_metadata_activity (v3 sources the sink owns are- dropped there), not here: the sink only follows a team's v3 sources, so a- sink-enabled team can still have non-v3 sources that this workflow must copy.- """+ """Evaluate whether the DuckLake data imports copy workflow should run for a team."""bind_contextvars(team_id=inputs.team_id)logger = LOGGER.bind()@@ -351,39 +344,9 @@ async def _prepare_data_imports_ducklake_metadata(await logger.ainfo("DuckLake copy requested but no schema_ids were provided - skipping")return []- # Resolve the same per-team schema the v3 sink uses (table_suffix-aware), so the- # historical copy and the live sink never diverge on schema name. All schemas in the- # batch belong to one team, so this is loop-invariant — resolve it once.+ # All schemas in the batch belong to one team, so resolve the destination once.ducklake_schema_name = await database_sync_to_async(duckgres_data_imports_schema)(inputs.team_id)- # Per-source mutual exclusion with the Duckgres v3 batch sink. The sink owns a- # registered team's v3 sources (it mirrors them live + backfills history), so- # drop those here; non-v3 sources stay on the copy workflow because the sink never- # touches them. A flagged team without a duckgres control-plane team row remains- # on this copy path until it completes the enable flow.- # is_pipeline_v3_enabled is the same gate the v3 router uses, so "copy" and- # "sink" never disagree on who owns a source (and both fail to "copy owns it").- # Lazy import: create_job_model pulls in temporalio.activity + the data_warehouse- # facade, which we don't want on this module's import path.- from products.warehouse_sources.backend.facade.pipelines import ( # noqa: PLC0415 — keeps the heavy temporal/facade deps off the import path- is_pipeline_v3_enabled,- )-- sink_enabled = is_dev_mode()- try:- gate_team = await database_sync_to_async(Team.objects.only("uuid", "organization_id").get)(id=inputs.team_id)- if not sink_enabled and await database_sync_to_async(is_duckgres_sink_team_member)(inputs.team_id):- sink_enabled = feature_enabled_or_false(- DUCKGRES_BATCH_SINK_FLAG,- str(gate_team.uuid),- groups={"organization": str(gate_team.organization_id), "project": str(gate_team.id)},- send_feature_flag_events=False,- )- except Exception as error:- await logger.awarning("Failed to resolve duckgres batch sink ownership; copying all schemas", error=str(error))- capture_exception(error)- sink_owns_source_type: dict[str, bool] = {}-model_list: list[DuckLakeCopyDataImportsMetadata] = []for schema_id in inputs.schema_ids:@@ -394,18 +357,6 @@ async def _prepare_data_imports_ducklake_metadata(normalized_name = schema.normalized_namesource_type = schema.source.source_type- if sink_enabled:- if source_type not in sink_owns_source_type:- sink_owns_source_type[source_type] = await database_sync_to_async(is_pipeline_v3_enabled)(- inputs.team_id, source_type- )- if sink_owns_source_type[source_type]:- await logger.ainfo(- "Skipping schema owned by the duckgres batch sink (v3 source)",- schema_id=str(schema.id),- source_type=source_type,- )- continuesource_table_uri = _data_imports_source_table_uri(schema)staging_uri = await database_sync_to_async(_resolve_data_imports_staging_uri)(source_table_uri, team_id=inputs.team_iddiff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.pyindex c645ceb08d69..e5b72f4ac5c9 100644--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.py+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.py@@ -21,7 +21,6 @@ from products.managed_warehouse.backend.logic.verification import (DuckLakeCopyVerificationParameter,DuckLakeCopyVerificationQuery,)-from products.managed_warehouse.backend.models import DuckgresServerfrom products.managed_warehouse.backend.storage import DeltaTableSnapshotWorkload, StagedDeltaTable, compute_staging_urifrom products.managed_warehouse.backend.temporal import ducklake_copy_data_imports_workflow as ducklake_modulefrom products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow import (@@ -138,83 +137,6 @@ async def test_ducklake_copy_data_imports_gate_respects_feature_flag(monkeypatchassert captured["send_feature_flag_events"] is False-async def test_prepare_excludes_only_v3_sink_owned_schemas(ateam, monkeypatch):- # On a sink-enabled team the duckgres sink owns v3 sources, so the copy workflow- # must drop those — but keep copying non-v3 sources the sink never follows. The- # exclusion is per-source, not the old wholesale team-level skip.- monkeypatch.setattr(ducklake_module, "_fetch_delta_partition_columns", lambda table_uri, *, team_id: ["created_at"])- monkeypatch.setattr(ducklake_module, "is_dev_mode", lambda: False)- # get_duckgres_server_by_team_org resolves the staging URI via its own module-level- # is_dev_mode, so it needs the same override or it short-circuits to None in tests.- monkeypatch.setattr("products.managed_warehouse.backend.common.is_dev_mode", lambda: False)- monkeypatch.setattr(- "products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.feature_enabled_or_false",- lambda *args, **kwargs: True, # duckgres-batch-sink on- )- from products.warehouse_sources.backend.facade import pipelines as warehouse_source_pipelines-- monkeypatch.setattr(- warehouse_source_pipelines, "is_pipeline_v3_enabled", lambda team_id, source_type: source_type == "Postgres"- )-- await database_sync_to_async(DuckgresServer.objects.create)(- organization_id=ateam.organization_id,- host="h",- username="root",- password="x",- bucket="bucket",- )- # Sink membership now lives in the duckgres control plane; toggle it at the seam the- # activity reads (membership resolution itself is covered in the enablement tests).- member = {"value": True}- monkeypatch.setattr(- "products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.is_duckgres_sink_team_member",- lambda team_id: member["value"],- )-- credential = await database_sync_to_async(DataWarehouseCredential.objects.create)(- team=ateam, access_key="k", access_secret="s"- )- v3_source = await database_sync_to_async(ExternalDataSource.objects.create)(- team=ateam, source_id="v3", connection_id="c1", source_type="Postgres", status="Running"- )- v3_schema = await database_sync_to_async(ExternalDataSchema.objects.create)(team=ateam, name="pg", source=v3_source)- non_v3_source = await database_sync_to_async(ExternalDataSource.objects.create)(- team=ateam, source_id="nv3", connection_id="c2", source_type="Stripe", status="Running"- )- non_v3_table = await database_sync_to_async(DataWarehouseTable.objects.create)(- team=ateam,- name="charges",- format="Delta",- url_pattern="s3://bucket/path",- credential=credential,- external_data_source=non_v3_source,- columns={"id": {"clickhouse": "Int64", "hogql": "IntegerDatabaseField"}},- )- non_v3_schema = await database_sync_to_async(ExternalDataSchema.objects.create)(- team=ateam,- name="charges",- source=non_v3_source,- table=non_v3_table,- sync_type=ExternalDataSchema.SyncType.INCREMENTAL,- sync_type_config={"incremental_field": "created_at", "incremental_field_type": "DateTime"},- )-- inputs = DataImportsDuckLakeCopyInputs(team_id=ateam.id, job_id="job", schema_ids=[v3_schema.id, non_v3_schema.id])-- result = await prepare_data_imports_ducklake_metadata_activity(inputs)-- # v3 source dropped (sink owns it); non-v3 source still copied.- assert [m.source_schema_id for m in result] == [str(non_v3_schema.id)]-- member["value"] = False- result_without_membership = await prepare_data_imports_ducklake_metadata_activity(inputs)-- assert {m.source_schema_id for m in result_without_membership} == {str(v3_schema.id), str(non_v3_schema.id)}--@pytest.mark.asyncio@pytest.mark.django_dbasync def test_prepare_data_imports_ducklake_metadata_activity_basic(ateam, monkeypatch):@@ -1517,8 +1439,6 @@ async def test_ducklake_copy_data_imports_workflow_runs_when_feature_flag_enablemonkeypatch.setattr(ducklake_module,"feature_enabled_or_false",- # Key-aware: the gate checks the duckgres-batch-sink exclusion first,- # and a catch-all True would wrongly trip it.lambda key, *args, **kwargs: key == "ducklake-data-imports-copy-workflow",)monkeypatch.setattr(ducklake_module, "prepare_data_imports_ducklake_metadata_activity", metadata_stub)@@ -1610,8 +1530,6 @@ async def test_ducklake_copy_data_imports_workflow_calls_cleanup_after_verify(momonkeypatch.setattr(ducklake_module,"feature_enabled_or_false",- # Key-aware: the gate checks the duckgres-batch-sink exclusion first,- # and a catch-all True would wrongly trip it.lambda key, *args, **kwargs: key == "ducklake-data-imports-copy-workflow",)monkeypatch.setattr(ducklake_module, "prepare_data_imports_ducklake_metadata_activity", metadata_stub)diff --git a/products/managed_warehouse/backend/tests/test_api.py b/products/managed_warehouse/backend/tests/test_api.pyindex 6e283c443d6c..a10ad398bfb3 100644--- a/products/managed_warehouse/backend/tests/test_api.py+++ b/products/managed_warehouse/backend/tests/test_api.py@@ -3,12 +3,7 @@ from unittest.mock import patchfrom posthog.models import Organization-from products.managed_warehouse.backend.facade.api import (- get_duckgres_query_server_config,- get_stored_warehouse_config,- has_provisioned_warehouse,- sink_concurrency_by_trusted_organization_ids,-)+from products.managed_warehouse.backend.facade.api import get_duckgres_query_server_config, get_stored_warehouse_configfrom products.managed_warehouse.backend.facade.contracts import DuckgresStoredServerConfigfrom products.managed_warehouse.backend.models import DuckgresServer@@ -51,7 +46,6 @@ def test_stored_warehouse_config_maps_connection_and_catalog_without_returning_tcatalog_password="catalog-password",bucket="managed-warehouse-bucket",bucket_region="eu-central-1",- sink_max_concurrency=9,)with patch("products.managed_warehouse.backend.common.is_dev_mode", return_value=False):@@ -63,31 +57,4 @@ def test_stored_warehouse_config_maps_connection_and_catalog_without_returning_tassert stored.catalog.host == "catalog.example.com"assert stored.bucket is not Noneassert stored.bucket.bucket == "managed-warehouse-bucket"- assert stored.sink_max_concurrency == 9assert not hasattr(stored, "save")---def test_sink_concurrency_uses_only_the_trusted_organization_ids() -> None:- trusted_organization = Organization.objects.create(name="Trusted")- untrusted_organization = Organization.objects.create(name="Untrusted")- DuckgresServer.objects.create(- organization=trusted_organization,- host="trusted.example.com",- username="root",- password="password",- sink_max_concurrency=3,- )- DuckgresServer.objects.create(- organization=untrusted_organization,- host="untrusted.example.com",- username="root",- password="password",- sink_max_concurrency=99,- )-- assert sink_concurrency_by_trusted_organization_ids([str(trusted_organization.id)]) == {- str(trusted_organization.id): 3- }- with patch("products.managed_warehouse.backend.facade.api.is_dev_mode", return_value=False):- assert has_provisioned_warehouse(trusted_organization.id) is Truediff --git a/products/managed_warehouse/backend/tests/test_sink_state.py b/products/managed_warehouse/backend/tests/test_sink_state.pydeleted file mode 100644index 477ca1c66eb1..000000000000--- a/products/managed_warehouse/backend/tests/test_sink_state.py+++ /dev/null@@ -1,90 +0,0 @@-from uuid import uuid4--import pytest-from freezegun import freeze_time--from django.db import connection-from django.test.utils import CaptureQueriesContext--from products.managed_warehouse.backend.facade import sink_state-from products.managed_warehouse.backend.facade.contracts import DuckgresSinkState, DuckgresSinkStateCreateInput-from products.managed_warehouse.backend.facade.testing import create_sink_state, get_sink_state---def test_mark_sink_state_primed_is_pinned_to_the_backfill_generation() -> None:- state = create_sink_state(- DuckgresSinkStateCreateInput(- team_id=1,- schema_id=uuid4(),- state=DuckgresSinkState.BACKFILLING,- backfill_run_uuid="run-r2",- chunk_count=2,- )- )-- assert not sink_state.mark_sink_state_primed(- state.schema_id,- backfill_run_uuid="run-r1",- chunks_applied=2,- )- stale = get_sink_state(state.id)- assert stale is not None- assert stale.state == DuckgresSinkState.BACKFILLING- assert stale.chunks_applied == 0-- assert sink_state.mark_sink_state_primed(- state.schema_id,- backfill_run_uuid="run-r2",- chunks_applied=2,- )- primed = get_sink_state(state.id)- assert primed is not None- assert primed.state == DuckgresSinkState.PRIMED- assert primed.chunks_applied == 2---def test_live_apply_stamp_does_not_change_lifecycle_updated_at() -> None:- with freeze_time("2026-01-01T00:00:00Z"):- state = create_sink_state(- DuckgresSinkStateCreateInput(- team_id=1,- schema_id=uuid4(),- state=DuckgresSinkState.PRIMED,- )- )-- with freeze_time("2026-01-02T00:00:00Z"):- sink_state.record_live_batch_applied(state.schema_id)-- stamped = get_sink_state(state.id)- assert stamped is not None- assert stamped.updated_at == state.updated_at- assert stamped.queue_last_applied_at is not None- assert stamped.queue_last_applied_at.isoformat() == "2026-01-02T00:00:00+00:00"---def test_list_sink_backfill_run_references_selects_only_required_fields() -> None:- state = create_sink_state(- DuckgresSinkStateCreateInput(- team_id=1,- schema_id=uuid4(),- state=DuckgresSinkState.BACKFILLING,- backfill_run_uuid="run-1",- last_error="large error payload",- )- )-- with CaptureQueriesContext(connection) as queries:- references = sink_state.list_sink_backfill_run_references([state.team_id])-- assert [(reference.schema_id, reference.backfill_run_uuid) for reference in references] == [- (state.schema_id, "run-1")- ]- assert len(queries) == 1- sql = queries[0]["sql"]- assert '"schema_id"' in sql- assert '"backfill_run_uuid"' in sql- assert '"last_error"' not in sqldiff --git a/products/warehouse_sources/backend/facade/pipelines.py b/products/warehouse_sources/backend/facade/pipelines.pyindex 546539faa4e6..4fd8b7081c23 100644--- a/products/warehouse_sources/backend/facade/pipelines.py+++ b/products/warehouse_sources/backend/facade/pipelines.py@@ -1,8 +1,8 @@"""Pipeline/metrics wiring for warehouse_sources.-Re-exports the data-import pipeline internals (v3 S3 helpers, health server, duckgres-enablement flag), the app-metric emitters, the CDC extraction input, and the pipeline-+Re-exports the data-import pipeline internals (v3 S3 helpers and health server),+the app-metric emitters, the CDC extraction input, and the pipeline-version + schema-sync helpers that sibling products (data_warehouse, error_tracking) andcore (the ducklake copy workflow) reach into while orchestrating or observing imports.@@ -24,8 +24,6 @@ _LAZY = {"CDCExtractionInput": "cdc.workflows","is_pipeline_v3_enabled": "workflow_activities.create_job_model","SyncNewSchemasActivityInputs": "workflow_activities.sync_new_schemas",- "DUCKGRES_BATCH_SINK_FLAG": "pipelines.pipeline_v3.duckgres.enablement",- "is_duckgres_sink_team_member": "pipelines.pipeline_v3.duckgres.enablement","finish_row_tracking": "row_tracking","HealthState": "pipelines.pipeline_v3.load.health","start_health_server": "pipelines.pipeline_v3.load.health",diff --git a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.pyindex 0c8c41d03c53..75ea7d2611d4 100644--- a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py+++ b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py@@ -1,13 +1,9 @@-"""Ops tooling for the v3 warehouse sources load queue (delta and duckgres sinks).+"""Ops tooling for the v3 warehouse sources load queue.Inspect queue state, count batches whose state disagrees with their job's,manually fail wedged runs, and force-release stuck coordination state (group-leases, the v3 Redis pipeline lock) from a toolbox pod. ``--sink duckgres``-drives the same verbs against the duckgres sink's status and lease tables; that-sink does not own the ExternalDataJob, the Redis pipeline lock, or the Temporal-workflow, so those steps (and check-mismatches entirely) are delta-only.-Mutating actions are dry-run by default and mirror the consumers' own-fail/reconcile semantics rather than inventing a second code path.+leases, the v3 Redis pipeline lock) from a toolbox pod. Mutating actions are+dry-run by default and mirror the consumer's own fail/reconcile semantics."""import sys@@ -30,9 +26,6 @@ from products.warehouse_sources.backend.models.external_data_source import Exterfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (RECOVERY_GRACE_SECONDS,)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (- DuckgresBatchQueue,-)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (mark_job_failed_if_not_terminal,)@@ -55,13 +48,7 @@ MAX_RUNS_DEFAULT = 20PRINT_LIMIT = 50DRY_RUN_MESSAGE = "Dry run - no changes written. Re-run with --live-run to apply."-SINK_DELTA = "delta"-SINK_DUCKGRES = "duckgres"--# Both queue classes expose the same sync ops helpers (get_active_runs,-# get_state_summary, get_leases, force_release_leases, get_stale_executing_sync,-# fail_run_sync), so the handlers drive whichever sink was selected.-SinkQueue = type[BatchQueue] | type[DuckgresBatchQueue]+QueueType = type[BatchQueue]@dataclass(frozen=True)@@ -96,9 +83,7 @@ class Command(BaseCommand):"Manage the v3 warehouse sources load queue: inspect state (status), count batches ""whose state disagrees with their job's (check-mismatches), manually fail wedged runs ""(fail-run/cancel), or force-release stuck group leases and v3 Redis "- "pipeline locks (release-locks). --sink duckgres targets the duckgres sink's queue "- "state instead of the delta loader's. Mutating actions are dry-run unless --live-run "- "is given."+ "pipeline locks (release-locks). Mutating actions are dry-run unless --live-run is given.")def add_arguments(self, parser: CommandParser) -> None:@@ -145,7 +130,7 @@ class Command(BaseCommand):fail_run.add_argument("--cancel-workflow",action="store_true",- help="Also request cancellation of each run's Temporal workflow (delta sink only)",+ help="Also request cancellation of each run's Temporal workflow",)# Temporal connection overrides (same flags as start_temporal_workflow): ops pods# often lack the worker pods' TEMPORAL_* env, so settings-based sync_connect@@ -176,7 +161,7 @@ class Command(BaseCommand):mismatches = subparsers.add_parser("check-mismatches",- help="Count batches whose queue state disagrees with their ExternalDataJob's status (delta sink only)",+ help="Count batches whose queue state disagrees with their ExternalDataJob's status",)self._add_target_args(mismatches)mismatches.add_argument(@@ -209,9 +194,7 @@ class Command(BaseCommand):)self._add_target_args(release)release.add_argument("--leases-only", action="store_true", help="Only release Postgres group leases")- release.add_argument(- "--redis-only", action="store_true", help="Only release v3 Redis pipeline locks (delta sink only)"- )+ release.add_argument("--redis-only", action="store_true", help="Only release v3 Redis pipeline locks")release.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")release.add_argument("--yes", action="store_true", help="Skip interactive confirmation")release.add_argument(@@ -222,12 +205,6 @@ class Command(BaseCommand):@staticmethoddef _add_target_args(parser: CommandParser) -> None:- parser.add_argument(- "--sink",- choices=[SINK_DELTA, SINK_DUCKGRES],- default=SINK_DELTA,- help="Which sink's queue state to manage: the delta loader (default) or the duckgres sink",- )parser.add_argument("--team-id", type=int, help="Scope by team")parser.add_argument("--schema-id", type=str, help="Scope by schema (requires --team-id)")parser.add_argument("--source-id", type=str, help="Scope by source (requires --team-id)")@@ -241,18 +218,15 @@ class Command(BaseCommand):if action == "cancel":action = "fail-run"- sink: str = options.get("sink") or SINK_DELTA- queue: SinkQueue = BatchQueue if sink == SINK_DELTA else DuckgresBatchQueue-with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:if action == "status":- self._handle_status(conn, options, sink=sink, queue=queue)+ self._handle_status(conn, options, queue=BatchQueue)elif action == "fail-run":- self._handle_fail_run(conn, options, sink=sink, queue=queue)+ self._handle_fail_run(conn, options, queue=BatchQueue)elif action == "check-mismatches":- self._handle_check_mismatches(conn, options, sink=sink, queue=queue)+ self._handle_check_mismatches(conn, options, queue=BatchQueue)elif action == "release-locks":- self._handle_release_locks(conn, options, sink=sink, queue=queue)+ self._handle_release_locks(conn, options, queue=BatchQueue)# -- targeting --------------------------------------------------------------@@ -341,7 +315,7 @@ class Command(BaseCommand):return list(jobs)def _collect_fail_targets(- self, conn: psycopg.Connection[Any], scope: Scope, *, queue: SinkQueue, include_job_only: bool+ self, conn: psycopg.Connection[Any], scope: Scope, *, queue: QueueType) -> list[FailTarget]:runs = queue.get_active_runs(conn,@@ -374,16 +348,10 @@ class Command(BaseCommand):f"Run {scope.run_uuid!r} has no batches inside the queue retention window "f"({PARTITION_PRUNING_INTERVAL}) - nothing to fail.")- if include_job_only:- message += (- " If its ExternalDataJob is stuck in Running, target it via --team-id/--schema-id instead."- )+ message += " If its ExternalDataJob is stuck in Running, target it via --team-id/--schema-id instead."raise CommandError(message)return targets- if not include_job_only:- return targets-# Running jobs the queue knows nothing about (producer died before enqueueing,# or the job-status write never landed after the batches went terminal).known_job_ids = {t.job_id for t in targets}@@ -407,20 +375,15 @@ class Command(BaseCommand):# -- fail-run ---------------------------------------------------------------- def _handle_fail_run(- self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue- ) -> None:- is_delta = sink == SINK_DELTA+ def _handle_fail_run(self, conn: psycopg.Connection[Any], options: dict[str, Any], *, queue: QueueType) -> None:cancel_workflow: bool = options["cancel_workflow"]- if cancel_workflow and not is_delta:- raise CommandError("--cancel-workflow only applies to the delta sink; drop it or use --sink delta")scope = self._resolve_scope(options, allow_empty=options["only_stuck"])reason: str = options["reason"]live_run: bool = options["live_run"]force: bool = options["force"]- targets = self._collect_fail_targets(conn, scope, queue=queue, include_job_only=is_delta)+ targets = self._collect_fail_targets(conn, scope, queue=queue)if options["only_stuck"]:targets, skipped_active = self._filter_stuck(targets, grace_seconds=options["stuck_grace_seconds"])if skipped_active:@@ -448,7 +411,7 @@ class Command(BaseCommand):}verb = "Would fail" if not live_run else "Failing"- self.stdout.write(f"{verb} {len(targets)} run(s) [{sink} sink]:")+ self.stdout.write(f"{verb} {len(targets)} run(s):")for t in targets:job = jobs_by_id.get(t.job_id)job_status = job.status if job else "<job not found>"@@ -465,7 +428,7 @@ class Command(BaseCommand):)if t.schema_id:notes = []- if is_delta and t.workflow_run_id:+ if t.workflow_run_id:holder = get_v3_pipeline_lock_holder(t.team_id, t.schema_id)if holder is None:notes.append("redis lock unheld")@@ -483,12 +446,6 @@ class Command(BaseCommand):if notes:self.stdout.write(f" -> {'; '.join(notes)}")- if not is_delta:- self.stdout.write(- "Note: failing duckgres runs leaves the ExternalDataJob untouched; "- "retry failed duckgres batches later with reset_duckgres_failed_runs."- )-if not live_run:self.stdout.write(DRY_RUN_MESSAGE)return@@ -497,10 +454,9 @@ class Command(BaseCommand):for t in targets:self.stdout.write(f"run={t.run_uuid or '-'} job={t.job_id}:")- self._fail_target(conn, t, reason=reason, queue=queue, is_delta=is_delta)+ self._fail_target(conn, t, reason=reason, queue=queue)logger.info("manage_warehouse_queue_fail_run",- sink=sink,run_uuid=t.run_uuid,job_id=t.job_id,team_id=t.team_id,@@ -518,7 +474,7 @@ class Command(BaseCommand):self.stdout.write(self.style.SUCCESS(summary))def _release_leases_for(- self, conn: psycopg.Connection[Any], targets: list[FailTarget], *, queue: SinkQueue, force: bool+ self, conn: psycopg.Connection[Any], targets: list[FailTarget], *, queue: QueueType, force: bool) -> tuple[int, int]:"""Drop the group leases the just-failed targets held. Returns (released, skipped_live)."""pair_set = {(t.team_id, t.schema_id) for t in targets if t.schema_id}@@ -556,8 +512,7 @@ class Command(BaseCommand):target: FailTarget,*,reason: str,- queue: SinkQueue,- is_delta: bool,+ queue: QueueType,) -> None:"""Mirror the consumer's fail path; each step isolated so one failure doesn't abort the rest."""if target.run_uuid:@@ -568,10 +523,6 @@ class Command(BaseCommand):logger.exception("manage_warehouse_queue_fail_run_queue_write_failed", run_uuid=target.run_uuid)self.stdout.write(self.style.ERROR(" queue: FAILED to write failed statuses (see logs)"))- if not is_delta:- # The duckgres sink doesn't own the job, the redis lock, or the workflow.- return-try:transitioned = mark_job_failed_if_not_terminal(job_id=target.job_id, team_id=target.team_id, error=reason)self.stdout.write(" job: marked Failed" if transitioned else " job: already terminal - left unchanged")@@ -653,7 +604,7 @@ class Command(BaseCommand):# -- check-mismatches -------------------------------------------------------def _handle_check_mismatches(- self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue+ self, conn: psycopg.Connection[Any], options: dict[str, Any], *, queue: QueueType) -> None:"""Report (and optionally repair) runs whose queue state disagrees with their job's status.@@ -669,19 +620,11 @@ class Command(BaseCommand):reported only: the job may have been hard-deleted or the id may becorrupt, and guessing is worse than surfacing it."""- if sink != SINK_DELTA:- raise CommandError(- "check-mismatches only applies to the delta sink: the duckgres sink does not own the "- "ExternalDataJob, and its batches legitimately outlive a Completed delta job."- )-scope = self._resolve_scope(options, allow_empty=True)grace: int = options["grace_seconds"]live_run: bool = options["live_run"]- # include_job_only pulls in the Running V3 jobs the queue knows nothing- # about, which is exactly class B; the queue-visible runs give A and C.- targets = self._collect_fail_targets(conn, scope, queue=queue, include_job_only=True)+ targets = self._collect_fail_targets(conn, scope, queue=queue)jobs_by_id = {str(j.id): j for j in ExternalDataJob.objects.filter(id__in=[t.job_id for t in targets])}class_a: list[FailTarget] = []@@ -705,7 +648,7 @@ class Command(BaseCommand):class_c, skipped_c = self._filter_stuck(class_c, grace_seconds=grace)skipped = skipped_a + skipped_b + skipped_c- self.stdout.write(self.style.MIGRATE_HEADING(f"Mismatches [{sink} sink] (grace {grace}s)"))+ self.stdout.write(self.style.MIGRATE_HEADING(f"Mismatches (grace {grace}s)"))a_batches = sum(t.pending_batches for t in class_a)c_batches = sum(t.pending_batches for t in class_c)self.stdout.write(f" A: terminal job, non-terminal batches {len(class_a)} run(s), {a_batches} batch(es)")@@ -780,11 +723,10 @@ class Command(BaseCommand):raced += 1continueself.stdout.write(f"run={t.run_uuid or '-'} job={t.job_id}:")- self._fail_target(conn, t, reason=reason, queue=queue, is_delta=True)+ self._fail_target(conn, t, reason=reason, queue=queue)repaired.append(t)logger.info("manage_warehouse_queue_check_mismatches",- sink=sink,run_uuid=t.run_uuid,job_id=t.job_id,team_id=t.team_id,@@ -803,7 +745,7 @@ class Command(BaseCommand):summary += f" Skipped {skipped_live} LIVE lease(s)."self.stdout.write(self.style.SUCCESS(summary))- def _job_has_pending_batches(self, conn: psycopg.Connection[Any], target: FailTarget, *, queue: SinkQueue) -> bool:+ def _job_has_pending_batches(self, conn: psycopg.Connection[Any], target: FailTarget, *, queue: QueueType) -> bool:"""True if the queue now holds non-terminal batches for this job's schema.Used to re-check a class B (job-only) target at repair time so a job that@@ -818,13 +760,10 @@ class Command(BaseCommand):# -- release-locks ----------------------------------------------------------def _handle_release_locks(- self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue+ self, conn: psycopg.Connection[Any], options: dict[str, Any], *, queue: QueueType) -> None:- is_delta = sink == SINK_DELTAif options["leases_only"] and options["redis_only"]:raise CommandError("--leases-only and --redis-only are mutually exclusive")- if options["redis_only"] and not is_delta:- raise CommandError("--redis-only only applies to the delta sink; the duckgres sink has no redis lock")scope = self._resolve_scope(options, allow_empty=False)if scope.run_uuid:raise CommandError("release-locks targets (team, schema) pairs; --run-uuid is not supported here")@@ -837,7 +776,7 @@ class Command(BaseCommand):live_run: bool = options["live_run"]force: bool = options["force"]check_leases = not options["redis_only"]- check_redis = is_delta and not options["leases_only"]+ check_redis = not options["leases_only"]# workflow_run_ids of Running jobs, per schema: a redis lock held by one of# these tokens belongs to live work and needs --force.@@ -909,7 +848,6 @@ class Command(BaseCommand):)logger.info("manage_warehouse_queue_release_locks",- sink=sink,released_leases=released_leases,released_locks=released_locks,team_id=scope.team_id,@@ -920,7 +858,7 @@ class Command(BaseCommand):)def _resolve_lock_pairs(- self, conn: psycopg.Connection[Any], scope: Scope, *, queue: SinkQueue+ self, conn: psycopg.Connection[Any], scope: Scope, *, queue: QueueType) -> list[tuple[int, str]]:"""(team_id, schema_id) pairs to check for stuck coordination state."""if scope.team_id is not None:@@ -955,10 +893,7 @@ class Command(BaseCommand):# -- status ------------------------------------------------------------------ def _handle_status(- self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue- ) -> None:- is_delta = sink == SINK_DELTA+ def _handle_status(self, conn: psycopg.Connection[Any], options: dict[str, Any], *, queue: QueueType) -> None:scope = self._resolve_scope(options, allow_empty=True)runs = queue.get_active_runs(@@ -978,7 +913,7 @@ class Command(BaseCommand):if summary_schema_ids is None and (scope.source_type or scope.run_uuid):summary_schema_ids = sorted({r.schema_id for r in runs})- self.stdout.write(self.style.MIGRATE_HEADING(f"Queue summary [{sink} sink] (within retention window)"))+ self.stdout.write(self.style.MIGRATE_HEADING("Queue summary (within retention window)"))summary = queue.get_state_summary(conn, team_id=scope.team_id, schema_ids=summary_schema_ids)if not summary:self.stdout.write(" no batches in scope")@@ -1005,13 +940,9 @@ class Command(BaseCommand):self.stdout.write(f" ... and {len(runs) - PRINT_LIMIT} more")known_job_ids = {r.job_id for r in runs}- # Delta-only: Running V3 jobs belong to the delta path, and a run-uuid scope- # carries no team/schema constraint, so _running_v3_jobs would return every- # Running V3 job in the fleet — skip the section.+ # A run-uuid scope carries no team/schema constraint, so skip the fleet-wide job query.orphan_jobs = (- []- if scope.run_uuid or not is_delta- else [j for j in self._running_v3_jobs(scope) if str(j.id) not in known_job_ids]+ [] if scope.run_uuid else [j for j in self._running_v3_jobs(scope) if str(j.id) not in known_job_ids])if orphan_jobs:self.stdout.write(@@ -1025,7 +956,7 @@ class Command(BaseCommand):f"workflow_run_id={job.workflow_run_id or '-'}")- self.stdout.write(self.style.MIGRATE_HEADING(f"Group leases [{sink} sink]"))+ self.stdout.write(self.style.MIGRATE_HEADING("Group leases"))leases = queue.get_leases(conn, team_id=scope.team_id, schema_ids=summary_schema_ids)if not leases:self.stdout.write(" none in scope")@@ -1036,31 +967,30 @@ class Command(BaseCommand):f"(expires {lease.expires_at.isoformat()})")- if is_delta:- self.stdout.write(self.style.MIGRATE_HEADING("Redis pipeline locks"))- workflow_tokens: dict[tuple[int, str], set[str]] = {}- for r in runs:- if r.workflow_run_id:- workflow_tokens.setdefault((r.team_id, r.schema_id), set()).add(r.workflow_run_id)- for job in orphan_jobs:- if job.schema_id and job.workflow_run_id:- workflow_tokens.setdefault((job.team_id, str(job.schema_id)), set()).add(job.workflow_run_id)- lock_pairs = sorted(- {(r.team_id, r.schema_id) for r in runs}- | {(lease.team_id, lease.schema_id) for lease in leases}- | {(job.team_id, str(job.schema_id)) for job in orphan_jobs if job.schema_id}- )[:PRINT_LIMIT]- held_any = False- for team_id, schema_id in lock_pairs:- holder = get_v3_pipeline_lock_holder(team_id, schema_id)- if holder is None:- continue- held_any = True- known = holder in workflow_tokens.get((team_id, schema_id), set())- note = "" if known else " - token matches no known active workflow_run_id (stale-lock smell)"- self.stdout.write(f" team={team_id} schema={schema_id} holder={holder!r}{note}")- if not held_any:- self.stdout.write(" none held for in-scope pairs")+ self.stdout.write(self.style.MIGRATE_HEADING("Redis pipeline locks"))+ workflow_tokens: dict[tuple[int, str], set[str]] = {}+ for r in runs:+ if r.workflow_run_id:+ workflow_tokens.setdefault((r.team_id, r.schema_id), set()).add(r.workflow_run_id)+ for job in orphan_jobs:+ if job.schema_id and job.workflow_run_id:+ workflow_tokens.setdefault((job.team_id, str(job.schema_id)), set()).add(job.workflow_run_id)+ lock_pairs = sorted(+ {(r.team_id, r.schema_id) for r in runs}+ | {(lease.team_id, lease.schema_id) for lease in leases}+ | {(job.team_id, str(job.schema_id)) for job in orphan_jobs if job.schema_id}+ )[:PRINT_LIMIT]+ held_any = False+ for team_id, schema_id in lock_pairs:+ holder = get_v3_pipeline_lock_holder(team_id, schema_id)+ if holder is None:+ continue+ held_any = True+ known = holder in workflow_tokens.get((team_id, schema_id), set())+ note = "" if known else " - token matches no known active workflow_run_id (stale-lock smell)"+ self.stdout.write(f" team={team_id} schema={schema_id} holder={holder!r}{note}")+ if not held_any:+ self.stdout.write(" none held for in-scope pairs")grace: int = options["stale_grace_seconds"]stale = queue.get_stale_executing_sync(diff --git a/products/warehouse_sources/backend/management/commands/reset_duckgres_failed_runs.py b/products/warehouse_sources/backend/management/commands/reset_duckgres_failed_runs.pydeleted file mode 100644index 2b98fa87d8ae..000000000000--- a/products/warehouse_sources/backend/management/commands/reset_duckgres_failed_runs.py+++ /dev/null@@ -1,124 +0,0 @@-from django.core.exceptions import ValidationError-from django.core.management.base import BaseCommand, CommandError--import psycopg-import structlog--from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL--from products.managed_warehouse.backend.facade import sink_state-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (- DUCKGRES_STATUS_TABLE,- DUCKGRES_STATUS_VIEW,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- BATCH_TABLE,- PARTITION_PRUNING_INTERVAL,-)--logger = structlog.get_logger(__name__)---class Command(BaseCommand):- help = (- "Un-stick a permanently failed Duckgres sink run: writes fresh 'waiting_retry' "- "status rows (attempt reset to 0) for its failed batches so the consumer picks "- "them up again. Only works while the batches are inside the queue retention "- "window — after that, heal via a full resync of the schema."- )-- def add_arguments(self, parser):- parser.add_argument("--run-uuid", type=str, help="Reset all failed duckgres batches of this run")- parser.add_argument("--team-id", type=int, help="Scope by team (with --schema-id)")- parser.add_argument("--schema-id", type=str, help="Reset all failed duckgres runs of this schema")- parser.add_argument("--dry-run", action="store_true", help="Report what would be reset without writing")- parser.add_argument(- "--replan-backfill",- metavar="SCHEMA_ID",- help="Retire the schema's current backfill run and re-enter backfill planning "- "(use when extracts were lost to retention or the backfill is wedged)",- )-- def handle(self, *args, **options):- replan_schema = options.get("replan_backfill")- if replan_schema:- try:- state = sink_state.get_sink_state(replan_schema)- except (ValueError, ValidationError) as e:- raise CommandError(f"No duckgres sink state for schema {replan_schema!r}: {e}")- if state is None:- raise CommandError(f"No duckgres sink state for schema {replan_schema!r}")- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import ( # noqa: PLC0415 — only needed for the optional --replan-backfill path- replan_backfill,- )-- if options.get("dry_run"):- self.stdout.write(- f"Would retire backfill run {state.backfill_run_uuid!r} "- f"(state={state.state}, applied={state.chunks_applied}/{state.chunk_count}) "- "and re-enter planning. Dry run — no changes written."- )- return- replan_backfill(replan_schema)- self.stdout.write(self.style.SUCCESS(f"Schema {replan_schema} re-entered backfill planning."))- return-- run_uuid = options.get("run_uuid")- team_id = options.get("team_id")- schema_id = options.get("schema_id")- dry_run = options.get("dry_run", False)-- if not run_uuid and not (team_id and schema_id):- raise CommandError("Provide --run-uuid, or both --team-id and --schema-id")-- filters = ["dgs.job_state = 'failed'", f"b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'"]- params: dict = {}- if run_uuid:- filters.append("b.run_uuid = %(run_uuid)s")- params["run_uuid"] = run_uuid- if team_id:- filters.append("b.team_id = %(team_id)s")- params["team_id"] = team_id- if schema_id:- filters.append("b.schema_id = %(schema_id)s")- params["schema_id"] = schema_id-- where = " AND ".join(filters)- select_sql = f"""- SELECT dgs.batch_id, b.run_uuid, b.batch_index, b.s3_path- FROM {DUCKGRES_STATUS_VIEW} dgs- JOIN {BATCH_TABLE} b ON b.id = dgs.batch_id- WHERE {where}- ORDER BY b.run_uuid, b.batch_index- """-- with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:- rows = conn.execute(select_sql, params).fetchall()- if not rows:- self.stdout.write("No failed duckgres batches match — nothing to reset.")- return-- self.stdout.write(f"{len(rows)} failed duckgres batch(es) across {len({r[1] for r in rows})} run(s):")- for batch_id, r_uuid, batch_index, s3_path in rows:- self.stdout.write(f" run={r_uuid} batch_index={batch_index} batch_id={batch_id} s3={s3_path}")-- if dry_run:- self.stdout.write("Dry run — no changes written.")- return-- cursor = conn.execute(- f"""- INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, error_response)- SELECT dgs.batch_id, 'waiting_retry', 0,- jsonb_build_object('error', 'manually reset via reset_duckgres_failed_runs')- FROM {DUCKGRES_STATUS_VIEW} dgs- JOIN {BATCH_TABLE} b ON b.id = dgs.batch_id- WHERE {where}- """,- params,- )- self.stdout.write(self.style.SUCCESS(f"Reset {cursor.rowcount} batch(es) to waiting_retry (attempt 0)."))- self.stdout.write(- "Note: if any batch's S3 extract has already been pruned, its retry will fail again — "- "heal those schemas with a full resync instead."- )diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_duckgres_load.py b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_duckgres_load.pydeleted file mode 100644index f465408c25e9..000000000000--- a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_duckgres_load.py+++ /dev/null@@ -1,137 +0,0 @@-import asyncio--from django.core.management.base import BaseCommand--import structlog--from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL-from posthog.temporal.common.logger import configure_logger--from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (- DuckgresBatchConsumer,- DuckgresConsumerConfig,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.load import process_batch-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.health import (- HealthState,- start_health_server,-)--logger = structlog.get_logger(__name__)--# The sink exists to survive duckgres maintenance windows: defaults give ~3h of-# retry coverage (8 attempts, 300s * attempt backoff) instead of the engine's-# <2min, because a max-attempts failure permanently gaps incremental tables.-DEFAULT_MAX_ATTEMPTS = 8-DEFAULT_RETRY_BACKOFF_SECONDS = 300-# A duckgres MERGE can legitimately run for minutes; recovery must not hand the-# batch to another pod while the first is still writing.-DEFAULT_RECOVERY_GRACE_SECONDS = 900-# A single batch wedged longer than this fails liveness so the pod restarts and-# the recovery sweep reassigns the batch.-DEFAULT_STUCK_BATCH_TIMEOUT_SECONDS = 1800.0---class Command(BaseCommand):- help = "Run the warehouse sources Duckgres batch consumer"-- def add_arguments(self, parser):- parser.add_argument(- "--max-concurrency",- type=int,- default=16,- help="Maximum number of (team_id, schema_id) groups processed concurrently (default: 16)",- )- parser.add_argument(- "--poll-interval",- type=float,- default=2.0,- help="Seconds between poll cycles when idle (default: 2.0)",- )- parser.add_argument(- "--poll-limit",- type=int,- default=50,- help="Maximum batches fetched per poll cycle (default: 50)",- )- parser.add_argument(- "--max-attempts",- type=int,- default=DEFAULT_MAX_ATTEMPTS,- help=f"Maximum processing attempts per batch before failing the Duckgres run (default: {DEFAULT_MAX_ATTEMPTS})",- )- parser.add_argument(- "--retry-backoff",- type=int,- default=DEFAULT_RETRY_BACKOFF_SECONDS,- help=f"Base seconds of retry backoff, multiplied by attempt (default: {DEFAULT_RETRY_BACKOFF_SECONDS})",- )- parser.add_argument(- "--recovery-grace",- type=int,- default=DEFAULT_RECOVERY_GRACE_SECONDS,- help=f"Seconds an 'executing' batch must be stale before recovery reassigns it (default: {DEFAULT_RECOVERY_GRACE_SECONDS})",- )- parser.add_argument(- "--stuck-batch-timeout",- type=float,- default=DEFAULT_STUCK_BATCH_TIMEOUT_SECONDS,- help=f"Seconds a single batch may run before the pod stops reporting healthy (default: {DEFAULT_STUCK_BATCH_TIMEOUT_SECONDS})",- )- parser.add_argument(- "--health-port",- type=int,- default=8080,- help="Port for the health check HTTP server (default: 8080)",- )- parser.add_argument(- "--health-timeout",- type=float,- default=60.0,- help="Health check timeout in seconds (default: 60.0)",- )-- def handle(self, *args, **options):- health_port = options["health_port"]- health_timeout = options["health_timeout"]-- config = DuckgresConsumerConfig(- database_url=WAREHOUSE_SOURCES_DATABASE_URL,- max_concurrency=options["max_concurrency"],- poll_interval_seconds=options["poll_interval"],- poll_limit=options["poll_limit"],- max_attempts=options["max_attempts"],- retry_backoff_base_seconds=options["retry_backoff"],- recovery_grace_seconds=options["recovery_grace"],- stuck_batch_timeout_seconds=options["stuck_batch_timeout"],- health_port=health_port,- health_timeout_seconds=health_timeout,- )-- logger.info(- "warehouse_sources_duckgres_load_starting",- max_concurrency=config.max_concurrency,- poll_interval=config.poll_interval_seconds,- poll_limit=config.poll_limit,- max_attempts=config.max_attempts,- retry_backoff_base_seconds=config.retry_backoff_base_seconds,- recovery_grace_seconds=config.recovery_grace_seconds,- stuck_batch_timeout_seconds=config.stuck_batch_timeout_seconds,- health_port=health_port,- )-- health_state = HealthState(timeout_seconds=health_timeout)- start_health_server(port=health_port, health_state=health_state)-- consumer = DuckgresBatchConsumer(- config=config, process_batch=process_batch, health_reporter=health_state.report_healthy- )- asyncio.run(_run_consumer(consumer))---async def _run_consumer(consumer: DuckgresBatchConsumer) -> None:- # Route structlog through the Kafka -> ClickHouse log_entries pipeline so the- # per-batch contextvars the engine binds are user-visible, mirroring the Delta- # consumer's entrypoint.- configure_logger(loop=asyncio.get_running_loop())- await consumer.run()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/__init__.pydeleted file mode 100644index ea92af7a6bfc..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (- DuckgresBatchConsumer,- DuckgresConsumerConfig,-)--__all__ = ["DuckgresBatchConsumer", "DuckgresConsumerConfig"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.pydeleted file mode 100644index 7a817e9562dd..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py+++ /dev/null@@ -1,853 +0,0 @@-"""Backfill primer for the Duckgres batch sink — durable state machine.--Pre-existing incremental/append schemas have history in Delta that the sink's-per-batch stream will never replay. The primer backfills it with bounded-memory and resume-from-checkpoint. This module owns the lifecycle transitions and-reconciliation; the moving parts live in sibling modules:--- backfill_snapshot.py — Delta snapshot resolution and chunk planning (pure).-- backfill_queue.py — idempotent queue writes (pre-apply, enqueue, retire).-- batch_kind.py — the canonical live-vs-backfill batch discriminator.--Lifecycle (every transition is a compare-and-swap; the planner runs in every-consumer pod's maintenance tick with no leader election):-- PENDING_BACKFILL --lease CAS--> BACKFILLING(no run) [lease-reset on crash]- BACKFILLING(no run) --plan CAS--> BACKFILLING(run) [the durable plan:- run_uuid + snapshot_version + chunk_count, written- BEFORE any queue rows; reconcile replays pre-apply/enqueue from it]- BACKFILLING(run) --> PRIMED when chunks_applied == chunk_count (the last- chunk's apply marker shares the swap's transaction, so full- application proves the swap), or fast-path via mark_primed after the swap.- BACKFILLING(run) --> NEEDS_RESYNC when superseded by a LIVE replace run- (structured kind): the replace has only reached Delta and may still- fail in duckgres, so it heals to PRIMED through the resync path below- rather than flipping PRIMED on a not-yet-complete table.- *_ --> NEEDS_RESYNC for unbackfillable tables (deletion vectors) or a- superseding replace; heals to PRIMED only when a live replace-head run- has FULLY applied (its final marker reached duckgres-succeeded) —- replace-head runs bypass the blocked gate precisely so that healing- path can run.--PRIMED always means "the duckgres table is complete"; nothing else ever sets-it. Containment of pre-applied work is proven per batch from Delta commit-metadata at the pinned snapshot version (see backfill_queue.preapply_covered_batches).-"""--from __future__ import annotations--import random-from datetime import timedelta-from typing import Any--from django.conf import settings-from django.db import close_old_connections-from django.utils import timezone--import psycopg-import structlog-from prometheus_client import Gauge--from posthog.exceptions_capture import capture_exception--from products.managed_warehouse.backend.facade import sink_state-from products.managed_warehouse.backend.facade.contracts import (- DuckgresSinkBackfillPlanInput,- DuckgresSinkState,- DuckgresSinkStateCreateInput,- DuckgresSinkStateRecord,-)-from products.warehouse_sources.backend.models import ExternalDataSchema-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (- BACKFILL_JOB_ID,- REASON_COVERED_BY_SNAPSHOT,- backfill_run_uuid,- enqueue_chunks,- preapply_covered_batches,- retire_backfill_run,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (- BackfillUnsupportedError,- resolve_snapshot_plan,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (- LIVE_BATCH_SQL_PREDICATE,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (- RETIRE_KIND_SUPERSEDED_BY_REPLACE,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- BATCH_TABLE,- PARTITION_PRUNING_INTERVAL,-)--logger = structlog.get_logger(__name__)--MAX_CONCURRENT_BACKFILLS_PER_ORG = 3 # best-effort across pods (see _plan_pending)-# Global ceiling on backfills in flight across ALL orgs. Backfill chunks and live-# batches share the consumer's group-concurrency pool (BatchConsumerConfig.max_concurrency),-# so this bounds how much of the duckgres worker budget backfills may consume and-# reserves headroom for live application. Tune to (worker ceiling − live headroom);-# keep <= max_concurrency. The per-org cap then keeps one org from eating the whole budget.-MAX_CONCURRENT_BACKFILLS_GLOBAL = 5-# A claim that never produced a durable run plan within this window is-# considered crashed and is returned to PENDING by the reconciler. Planning is-# metadata-only (Delta log read + row inserts), so minutes of lease are ample.-PLANNING_LEASE_SECONDS = 900--# A schema with this many consecutive failed backfill attempts (and not primed)-# is classified "failing": its blocked backlog moves off the pageable gauges-# into the failing bucket, and the planner retries it with backoff instead of-# every tick. 3 rides out a single transient blip without flapping the buckets.-FAILING_THRESHOLD = 3-# Planner retry backoff for failing schemas: BASE * 2**(failures-1), capped.-# Never gives up — at the cap the schema retries every ~30min forever, so it-# self-heals the moment the underlying issue clears.-RETRY_BACKOFF_BASE_SECONDS = 30-RETRY_BACKOFF_CAP_SECONDS = 30 * 60--BACKFILL_SCHEMAS_GAUGE = Gauge(- "duckgres_backfill_schemas",- "Duckgres sink schemas per backfill lifecycle state",- labelnames=["state"],- multiprocess_mode="livemax",-)-# Visibility-only (dashboards / future UI). Deliberately unalerted: a stuck-# backfill is an operator-remediation queue, not a page — the pageable signal-# is the healthy blocked backlog in the consumer's gauges.-STUCK_BACKFILL_GAUGE = Gauge(- "duckgres_sink_stuck_backfill",- "Schemas whose backfill is persistently failing (failure streak at threshold, or parked in needs_resync)",- multiprocess_mode="livemax",-)-STUCK_BACKFILL_OLDEST_AGE_GAUGE = Gauge(- "duckgres_sink_stuck_oldest_age_seconds",- "Age of the oldest failing schema's failure streak (first_failed_at) — survives queue retention",- multiprocess_mode="livemax",-)--__all__ = [- "BACKFILL_JOB_ID",- "BackfillUnsupportedError",- "backfill_run_uuid",- "blocked_schema_ids",- "failing_schema_ids",- "mark_primed",- "mark_schema_diverged",- "replan_backfill",- "run_backfill_planner",- "sink_eligible_schema_ids",-]---def run_backfill_planner(team_ids: list[int] | None) -> None:- """One planner pass: bootstrap state rows, reconcile in-flight, plan pending.-- Per-schema failures are isolated; called from the consumer's maintenance- tick (sync_to_async, thread_sensitive=False).- """- close_old_connections()- if team_ids is not None and not team_ids:- return-- _bootstrap_state_rows(team_ids)- _reconcile(team_ids)- _plan_pending(team_ids)- _emit_state_gauge()---def blocked_schema_ids(team_ids: list[int] | None) -> list[str]:- """Schemas whose live batches the sink must not apply yet.-- A schema is blocked unless it has a PRIMED state row — including schemas- with no row at all, so there is no window between flag-flip and the first- planner pass where a pre-existing schema's live batches sneak in. The- queue grants one exception: replace-head runs bypass the block (they- rebuild the table from scratch, which is always safe and is the healing- path for NEEDS_RESYNC).- """- close_old_connections()- if team_ids is not None and not team_ids:- return []-- schemas = ExternalDataSchema.objects.exclude(deleted=True)- if team_ids is not None:- schemas = schemas.filter(team_id__in=team_ids)- primed_ids = set(sink_state.list_primed_schema_ids(team_ids))- return [str(sid) for sid in schemas.values_list("id", flat=True) if str(sid) not in primed_ids]---def failing_schema_ids(team_ids: list[int] | None) -> list[str]:- """Schemas whose blocked backlog is hard-blocked, not merely in-progress.-- A subset of blocked_schema_ids: the consumer subtracts these batches from- the pageable blocked gauges so a wedged schema cannot mask (or trigger) a- genuine-throughput page, and reports them in the failing bucket instead.- """- close_old_connections()- if team_ids is not None and not team_ids:- return []-- return sink_state.list_failing_schema_ids(team_ids, failing_threshold=FAILING_THRESHOLD)---def sink_eligible_schema_ids(team_ids: list[int]) -> list[str]:- """Schema ids whose (team, source_type) is on warehouse-pipelines-v3.-- The sink claims batches ONLY for these schemas, keeping consumption in- lockstep with the v3 routing flag — the same gate that decides which source- types the v3 pipeline produces for and which schemas get primed here. The- shared queue can hold batches for non-v3 source types (a source_type that- was v3 during an earlier flag window, or the flag-independent CDC writer);- without this gate the team-scoped claim applies them anyway, and replace-head- batches (full_refresh / first-ever incremental) even bypass the unprimed- block. Enabling a source_type later lets its schemas bootstrap, prime, and- begin live application through the normal path.-- Evaluated per (team_id, source_type) with a local cache — the same gate- ``_bootstrap_state_rows`` uses to decide priming, so consumption and priming- never disagree. Raises on app-DB errors so the caller keeps its previous- cached set; a transient blip must not silently empty the allow-list.-- Prod only: the consumer calls this with a concrete team list. Dev mode- (no team filter) is left ungated by the caller.- """- close_old_connections()- if not team_ids:- return []-- # Lazy import: create_job_model pulls in temporalio.activity + the data- # warehouse facade, kept off the planner module's import path.- from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import ( # noqa: PLC0415 — keeps the heavy temporal/facade deps off the import path- is_pipeline_v3_enabled,- )-- schemas = (- ExternalDataSchema.objects.exclude(deleted=True)- .filter(team_id__in=team_ids)- .values("id", "team_id", "source__source_type")- )- v3_enabled: dict[tuple[int, str], bool] = {}- eligible: list[str] = []- for schema in schemas.iterator(chunk_size=BOOTSTRAP_BATCH_SIZE):- key = (schema["team_id"], schema["source__source_type"])- if key not in v3_enabled:- v3_enabled[key] = is_pipeline_v3_enabled(schema["team_id"], schema["source__source_type"])- if v3_enabled[key]:- eligible.append(str(schema["id"]))- return eligible---def mark_primed(schema_id: str, *, run_uuid: str, chunks_applied: int | None = None) -> None:- """Fast path called by the processor right after the swap commits.-- CAS from BACKFILLING only — the reconciler is the authoritative healer,- and a late call must never clobber a state that has since moved on. The- CAS is also pinned to the run generation: a replan can retire run R1 and- plan R2 while R1's final chunk is still mid-swap (its duckgres transaction- cannot be cancelled), and R1's late mark_primed must not flip R2's row —- that would unblock live batches over a table R2's own swap later replaces,- silently dropping them.- """- sink_state.mark_sink_state_primed(- schema_id,- backfill_run_uuid=run_uuid,- chunks_applied=chunks_applied,- )---def mark_schema_diverged(schema_id: str, *, run_uuid: str, error: str) -> None:- """A LIVE run hard-failed in the sink: some of its batches applied and the- rest never will, so the duckgres table is durably behind Delta. Park the- schema in NEEDS_RESYNC — that blocks further live batches from compounding- the gap, classifies the schema failing (streak jumped to threshold: a- terminally failed run has no retry loop to ride out), and routes healing- through the existing path: the next fully-applied replace-head run- (full-refresh resync, or the schema's own next full_refresh sync) flips it- back to PRIMED.-- CAS from PRIMED only: a BACKFILLING schema's failures are the reconciler's- to escalate, and an already-parked schema must not have its streak anchor- or error overwritten.- """- close_old_connections()- flipped = sink_state.mark_sink_state_diverged(- schema_id,- run_uuid=run_uuid,- error=error,- failing_threshold=FAILING_THRESHOLD,- )- if flipped:- logger.warning(- "duckgres_sink_schema_diverged",- schema_id=schema_id,- run_uuid=run_uuid,- error=error[:500],- )---def replan_backfill(schema_id: str) -> None:- """Operator entrypoint: retire the current backfill run and re-enter planning.-- The next plan gets a fresh generation nonce, so an unadvanced Delta- version still yields a new, claimable run.- """- state = sink_state.get_sink_state(schema_id)- if state is None:- raise LookupError(f"No duckgres sink state for schema {schema_id!r}")- if state.backfill_run_uuid:- with psycopg.connect(- settings.WAREHOUSE_SOURCES_DATABASE_URL,- autocommit=True,- # These run inline in the consumer fetch path: a half-open connection- # must fail in minutes, not the OS TCP timeout (hours).- connect_timeout=30,- keepalives=1,- keepalives_idle=60,- keepalives_interval=15,- keepalives_count=4,- ) as conn:- retire_backfill_run(conn, run_uuid=state.backfill_run_uuid)- sink_state.reset_backfill_plan(state.id)---# ----------------------------------------------------------------------------# Bootstrap & planning-# ------------------------------------------------------------------------------BOOTSTRAP_BATCH_SIZE = 1000---def _bootstrap_state_rows(team_ids: list[int] | None) -> None:- """Create state rows for enabled teams' schemas that have none.-- Only schemas whose source is on warehouse-pipelines-v3 get a row: the sink- follows v3 sources only, so priming a non-v3 source would create state the- consumer never advances (and never primes).-- Straight to PRIMED when no priming is needed:- - full_refresh: every run's batch 0 replaces the table completely.- - no Delta table yet: the first sync creates everything.- - cdc: the sink rejects CDC batches outright; do not block the queue on it.-- Memory-bounded: a single team can own tens of thousands of schemas, so we- anti-join in Postgres to skip schemas that already have a state row, stream- the rest with a server-side cursor instead of materializing the whole set,- and flush in fixed batches so the in-flight list never grows unbounded.- """- # Lazy import: create_job_model pulls in temporalio.activity + the data_warehouse- # facade, which we don't want on the planner module's import path.- from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import ( # noqa: PLC0415 — keeps the heavy temporal/facade deps off the import path- is_pipeline_v3_enabled,- )-- schemas = sink_state.exclude_schemas_with_sink_state(ExternalDataSchema.objects.exclude(deleted=True))- if team_ids is not None:- schemas = schemas.filter(team_id__in=team_ids)- schema_values = schemas.values("id", "team_id", "sync_type", "table_id", "source__source_type")-- # The sink only follows v3 sources (warehouse-pipelines-v3 is evaluated per- # team+source_type), so only prime schemas the consumer will actually mirror.- # Memoized per (team_id, source_type) — the flag does a network eval, and a- # team has only a handful of source types, so this stays cheap even with many schemas.- v3_enabled: dict[tuple[int, str], bool] = {}-- def _source_is_v3(team_id: int, source_type: str) -> bool:- key = (team_id, source_type)- if key not in v3_enabled:- v3_enabled[key] = is_pipeline_v3_enabled(team_id, source_type)- return v3_enabled[key]-- created = 0- to_create: list[DuckgresSinkStateCreateInput] = []- for schema in schema_values.iterator(chunk_size=BOOTSTRAP_BATCH_SIZE):- if not _source_is_v3(schema["team_id"], schema["source__source_type"]):- continue- needs_backfill = schema["sync_type"] not in ("full_refresh", "cdc", None) and schema["table_id"] is not None- to_create.append(- DuckgresSinkStateCreateInput(- team_id=schema["team_id"],- schema_id=schema["id"],- state=(DuckgresSinkState.PENDING_BACKFILL if needs_backfill else DuckgresSinkState.PRIMED),- )- )- if len(to_create) >= BOOTSTRAP_BATCH_SIZE:- sink_state.bulk_create_sink_states(to_create)- created += len(to_create)- to_create = []-- if to_create:- sink_state.bulk_create_sink_states(to_create)- created += len(to_create)- if created:- logger.info("duckgres_backfill_bootstrapped", created=created)---def _retry_backoff_seconds(failures: int) -> float:- if failures <= 0:- return 0.0- base = min(RETRY_BACKOFF_BASE_SECONDS * 2 ** (failures - 1), RETRY_BACKOFF_CAP_SECONDS)- return base * random.uniform(0.8, 1.2)---def _plan_pending(team_ids: list[int] | None) -> None:- pending = sink_state.list_pending_sink_states(team_ids, limit=50)-- # Oldest-touched first so a failing schema cannot starve the rest of the slice.- for state in pending:- # Global ceiling: backfills share the consumer worker pool with live- # application, so once the global budget is full no org may claim —- # stop scanning this tick. Re-evaluated each iteration since earlier- # iterations may have claimed slots.- if _global_at_capacity():- break-- # Failing schemas retry with backoff instead of hammering a broken- # Delta table every tick. updated_at is the last-attempt anchor (each- # recorded failure bumps it). Never gives up: at the cap this is one- # attempt per ~30min forever, so it self-heals when the table recovers.- # auto_now makes updated_at nullable to the type checker only; a missing- # anchor means no backoff to honour, so attempt rather than skip forever.- last_attempt_at = state.updated_at- if (- state.consecutive_failures > 0- and last_attempt_at is not None- and timezone.now() < last_attempt_at + timedelta(seconds=_retry_backoff_seconds(state.consecutive_failures))- ):- continue-- org_id = state.organization_id- assert org_id is not None- if _org_at_capacity(org_id):- continue-- # Lease claim: exactly one pod proceeds past this line per schema.- claimed = sink_state.claim_pending_backfill(state.id)- if not claimed:- continue-- # Re-check both caps after winning the claim; the pre-checks raced against- # other pods. Excluding self (now BACKFILLING), revert if either the org or- # the global budget is already at capacity. (Still best-effort across pods —- # a transient over-the-cap backfill is wasteful, not incorrect.)- if _org_at_capacity(org_id, exclude_id=state.id) or _global_at_capacity(exclude_id=state.id):- _revert_to_pending(state.id)- continue-- try:- _plan_one(state)- except BackfillUnsupportedError as e:- sink_state.mark_backfill_unsupported(state.id, error=str(e))- logger.warning("duckgres_backfill_unsupported", schema_id=str(state.schema_id), error=str(e))- except Exception as e:- logger.exception("duckgres_backfill_plan_failed", schema_id=str(state.schema_id))- capture_exception(e)- _revert_to_pending(state.id, error=str(e)[:2000], record_failure=True)---def _org_at_capacity(org_id: Any, *, exclude_id: Any = None) -> bool:- """Is this org at its per-org backfill cap? Pass exclude_id to ignore the- just-claimed row when re-checking after a claim."""- return sink_state.is_backfill_capacity_reached(- MAX_CONCURRENT_BACKFILLS_PER_ORG,- organization_id=org_id,- exclude_id=exclude_id,- )---def _global_at_capacity(*, exclude_id: Any = None) -> bool:- """Is the global backfill budget (across all orgs) full? Counts every- BACKFILLING row, since all backfills draw from one shared worker pool."""- return sink_state.is_backfill_capacity_reached(- MAX_CONCURRENT_BACKFILLS_GLOBAL,- exclude_id=exclude_id,- )---def _revert_to_pending(state_id: Any, error: str | None = None, *, record_failure: bool = False) -> None:- """record_failure distinguishes a failed attempt from a neutral revert- (capacity re-check lost the race) — capacity is pacing, not failure, and- must not start a streak."""- sink_state.return_backfill_claim_to_pending(- state_id,- error=error,- record_failure=record_failure,- )---def _has_inflight_replace_run(conn: psycopg.Connection[Any], *, team_id: int, schema_id: str) -> bool:- """A replace-head live run that Delta accepted but duckgres has not finished.-- Batch 0 replace-shaped and delta-succeeded, with no terminal Delta failure,- duckgres-succeeded final marker (completion), or duckgres-failed batch for- the run. Planning must wait these out: the snapshot would cover the run's- head and orphan its tail (see the guard in _plan_one).- """- row = conn.execute(- f"""- SELECT 1- FROM {BATCH_TABLE} h- JOIN v_latest_source_batch_status hds ON hds.batch_id = h.id- WHERE h.team_id = %(team_id)s- AND h.schema_id = %(schema_id)s- AND h.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND h.batch_index = 0- AND h.is_final_batch = false- AND h.is_resume = false- AND (h.sync_type = 'full_refresh' OR (h.sync_type = 'incremental' AND h.is_first_ever_sync))- AND hds.job_state = 'succeeded'- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} x- JOIN v_latest_source_batch_status xds ON xds.batch_id = x.id- WHERE x.run_uuid = h.run_uuid- AND x.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND xds.job_state = 'failed'- )- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} f- JOIN v_latest_source_batch_duckgres_status fdgs ON fdgs.batch_id = f.id- WHERE f.run_uuid = h.run_uuid- AND f.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND f.is_final_batch = true- AND fdgs.job_state = 'succeeded'- )- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} x- JOIN v_latest_source_batch_duckgres_status xdgs ON xdgs.batch_id = x.id- WHERE x.run_uuid = h.run_uuid- AND x.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND xdgs.job_state = 'failed'- )- LIMIT 1- """,- {"team_id": team_id, "schema_id": schema_id},- ).fetchone()- return row is not None---def _plan_one(state: DuckgresSinkStateRecord) -> None:- """Runs only on the pod that won the lease claim.-- Ordering is crash-safety-critical:- 1. resolve the snapshot (no side effects),- 2. CAS the durable run plan onto the state row — the real claim,- 3. pre-apply covered batches, 4. enqueue chunks.- A crash after step 2 is healed by _reconcile_one (replay 3-4 from the- stored plan); a crash before it is healed by the planning lease.- """- schema = (- ExternalDataSchema.objects.select_related("source", "team").filter(deleted=False, id=state.schema_id).first()- )- if schema is None:- # Soft-deleted (or vanished) schema: its chunks would be unclaimable and- # the row would pin a backfill slot forever. The purge sweep in- # _reconcile retires the run and removes the state row.- logger.warning("duckgres_backfill_plan_skipped_deleted_schema", schema_id=str(state.schema_id))- return-- with psycopg.connect(- settings.WAREHOUSE_SOURCES_DATABASE_URL,- autocommit=True,- # These run inline in the consumer fetch path: a half-open connection- # must fail in minutes, not the OS TCP timeout (hours).- connect_timeout=30,- keepalives=1,- keepalives_idle=60,- keepalives_interval=15,- keepalives_count=4,- ) as conn:- if _has_inflight_replace_run(conn, team_id=schema.team_id, schema_id=str(state.schema_id)):- # Planning now would pin a snapshot mid-run and pre-apply the- # replace run's head: its post-snapshot tail would then apply into- # the doomed pre-swap table (the replace-head gate bypass admits- # it), and the swap would silently drop those rows while their- # apply markers prevent any re-apply. Defer until the run reaches- # a terminal duckgres state; the planner retries every tick.- logger.info(- "duckgres_backfill_plan_deferred_for_inflight_replace",- schema_id=str(state.schema_id),- team_id=schema.team_id,- )- return- plan = resolve_snapshot_plan(schema)- snapshot_version = plan.snapshot_version- chunks = plan.chunks- if not chunks:- # Empty Delta table: nothing to prime.- sink_state.mark_empty_backfill_primed(state.id)- return-- run_uuid = backfill_run_uuid(str(state.schema_id), snapshot_version)-- # Durable plan claim: only one pod can attach a run to this state row.- planned = sink_state.claim_backfill_plan(- state.id,- DuckgresSinkBackfillPlanInput(- snapshot_version=snapshot_version,- backfill_run_uuid=run_uuid,- chunk_count=len(chunks),- ),- )- if not planned:- return-- preapplied = preapply_covered_batches(- conn,- team_id=schema.team_id,- schema_id=str(state.schema_id),- covered_batches=plan.covered_batches,- reason=f"{REASON_COVERED_BY_SNAPSHOT} v{snapshot_version}",- )- inserted = enqueue_chunks(conn, schema, run_uuid, chunks)-- logger.info(- "duckgres_backfill_planned",- schema_id=str(state.schema_id),- team_id=schema.team_id,- run_uuid=run_uuid,- snapshot_version=snapshot_version,- chunk_count=len(chunks),- inserted=inserted,- preapplied_covered_batches=preapplied,- total_bytes=sum(c.byte_size for c in chunks),- )---# ----------------------------------------------------------------------------# Reconciliation-# ------------------------------------------------------------------------------def _purge_deleted_schema_states(conn: psycopg.Connection[Any], team_ids: list[int] | None) -> None:- """Drop sink state for soft-deleted schemas and retire their runs.-- Schema deletion has no signal into this state machine: a deleted schema's- chunks become unclaimable (the eligibility gate excludes deleted schemas),- so a BACKFILLING row would sit forever — invisible on the failing gauges- (zero failures) while permanently consuming one of the global backfill- slots, and its chunks would be re-enqueued after every queue prune. Five- routine source deletions would halt all backfill planning fleet-wide.- Deleting the row is safe: bootstrap re-creates PENDING_BACKFILL if the- schema ever comes back.- """- states = sink_state.list_sink_backfill_run_references(team_ids)- run_by_schema = {state.schema_id: state.backfill_run_uuid for state in states}- if not run_by_schema:- return- deleted_ids = list(- ExternalDataSchema.objects.filter(id__in=run_by_schema.keys(), deleted=True).values_list("id", flat=True)- )- for schema_id in deleted_ids:- run_uuid = run_by_schema[schema_id]- if run_uuid:- retire_backfill_run(conn, run_uuid=run_uuid)- sink_state.delete_sink_state(schema_id)- logger.warning("duckgres_backfill_state_purged_for_deleted_schema", schema_id=str(schema_id))---def _reconcile(team_ids: list[int] | None) -> None:- """Heal and progress every non-terminal state. Authoritative for PRIMED."""- # Half-claimed rows (crash between the lease CAS and the plan CAS) carry- # no run plan; after the lease they return to PENDING for a fresh attempt.- reset = sink_state.reset_stale_backfill_claims(team_ids, lease_seconds=PLANNING_LEASE_SECONDS)- if reset:- logger.warning("duckgres_backfill_stale_claims_reset", count=reset)-- rows = sink_state.list_reconciling_backfill_states(team_ids)- resync_rows = sink_state.list_needs_resync_sink_states(team_ids)-- with psycopg.connect(- settings.WAREHOUSE_SOURCES_DATABASE_URL,- autocommit=True,- # These run inline in the consumer fetch path: a half-open connection- # must fail in minutes, not the OS TCP timeout (hours).- connect_timeout=30,- keepalives=1,- keepalives_idle=60,- keepalives_interval=15,- keepalives_count=4,- ) as conn:- try:- _purge_deleted_schema_states(conn, team_ids)- except Exception as e:- logger.exception("duckgres_backfill_deleted_schema_purge_failed")- capture_exception(e)- if not rows and not resync_rows:- return- for state in rows:- try:- _reconcile_one(conn, state)- except Exception as e:- logger.exception("duckgres_backfill_reconcile_failed", schema_id=str(state.schema_id))- capture_exception(e)- for state in resync_rows:- try:- _reconcile_needs_resync(conn, state)- except Exception as e:- logger.exception("duckgres_backfill_resync_check_failed", schema_id=str(state.schema_id))- capture_exception(e)---def _reconcile_one(conn: psycopg.Connection[Any], state: DuckgresSinkStateRecord) -> None:- run_uuid = state.backfill_run_uuid- assert run_uuid is not None- applied_row = conn.execute(- "SELECT count(DISTINCT batch_index) FROM sourcebatchduckgresapply WHERE run_uuid = %s", [run_uuid]- ).fetchone()- applied = int(applied_row[0]) if applied_row else 0-- if state.chunk_count and applied >= state.chunk_count:- # Full application proves the swap committed (the last chunk's apply- # marker shares the swap's transaction). CAS so a stale pass can never- # resurrect a state another pod already advanced — pinned to the run- # the applied-count evidence was gathered for, so a replan that swapped- # generations mid-pass cannot be promoted on the old run's counts.- sink_state.mark_backfill_completed(- state.id,- backfill_run_uuid=run_uuid,- chunks_applied=applied,- )- return-- failed = conn.execute(- f"""- SELECT dgs.error_response->>'error', dgs.error_response->>'kind'- FROM v_latest_source_batch_duckgres_status dgs- JOIN {BATCH_TABLE} b ON b.id = dgs.batch_id- WHERE b.run_uuid = %s AND dgs.job_state = 'failed'- LIMIT 1- """,- [run_uuid],- ).fetchone()-- if failed is not None:- reason = failed[0] or ""- kind = failed[1]- if kind == RETIRE_KIND_SUPERSEDED_BY_REPLACE:- # A LIVE replace run retired the backfill. The replace rebuilds the- # table completely, but at this point it has only reached Delta — it- # may still fail in duckgres. Flipping straight to PRIMED here would- # unblock live batches over a stale/incomplete table if the replace- # later exhausts retries. Park in NEEDS_RESYNC so the resync path- # promotes to PRIMED only once the replace run's final marker reaches- # duckgres-succeeded (the same completion proof every PRIMED requires).- sink_state.mark_backfill_superseded(state.id)- logger.info(- "duckgres_backfill_superseded_by_live_refresh",- schema_id=str(state.schema_id),- run_uuid=run_uuid,- )- elif (- state.last_error != reason- or state.consecutive_failures < FAILING_THRESHOLD- or state.first_failed_at is None- ):- # Mid-backfill wedge: a duckgres 'failed' status is terminal, so this- # run will never progress on its own — classify the schema failing- # immediately (jump the streak to threshold rather than drip one per- # tick), else its backlog sits in the pageable healthy bucket forever.- # The condition gates re-writes so a steady wedge stops churning the row.- sink_state.record_terminal_backfill_failure(- state.id,- error=reason,- chunks_applied=applied,- failing_threshold=FAILING_THRESHOLD,- )- return-- # Healthy in-flight run: track progress and replay plan side effects lost- # to a crash or to 7-day queue retention (apply markers persist 30d, so- # resume is exact; all replayed writes are idempotent).- # count DISTINCT batch_index, not count(*): a duplicate chunk row must never- # inflate the count and mask a genuinely missing index, which would stop the- # replay from re-enqueueing it.- present_row = conn.execute(- f"SELECT count(DISTINCT batch_index) FROM {BATCH_TABLE} WHERE run_uuid = %s", [run_uuid]- ).fetchone()- present = int(present_row[0]) if present_row else 0- if state.chunk_count and present < state.chunk_count and state.snapshot_version is not None:- schema = ExternalDataSchema.objects.select_related("source").get(id=state.schema_id)- plan = resolve_snapshot_plan(schema, version=state.snapshot_version)- preapply_covered_batches(- conn,- team_id=state.team_id,- schema_id=str(state.schema_id),- covered_batches=plan.covered_batches,- reason=f"{REASON_COVERED_BY_SNAPSHOT} v{state.snapshot_version}",- )- chunks = plan.chunks- reinserted = enqueue_chunks(conn, schema, str(run_uuid), chunks)- if reinserted:- logger.info(- "duckgres_backfill_reenqueued_dropped_chunks",- schema_id=str(state.schema_id),- run_uuid=run_uuid,- reinserted=reinserted,- )-- if applied != state.chunks_applied:- # Chunks are landing again, so forward progress ends the failure streak.- sink_state.record_backfill_progress(- state.id,- chunks_applied=applied,- reset_failure_streak=applied > state.chunks_applied,- )---def _reconcile_needs_resync(conn: psycopg.Connection[Any], state: DuckgresSinkStateRecord) -> None:- """Flip NEEDS_RESYNC to PRIMED only when a replace run has FULLY applied.-- Replace-head runs bypass the blocked gate (jobs_db), so a user-triggered- full refresh can run while the schema is parked. Its final marker reaches- duckgres-succeeded only after every prior batch applied — that is the- completion proof, so PRIMED keeps its single meaning: the table is- complete.- """- live_predicate_f = LIVE_BATCH_SQL_PREDICATE.replace("b.", "f.")- done = conn.execute(- f"""- SELECT 1- FROM {BATCH_TABLE} f- JOIN v_latest_source_batch_duckgres_status fdgs ON f.id = fdgs.batch_id- WHERE f.team_id = %(team_id)s- AND f.schema_id = %(schema_id)s- AND f.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND {live_predicate_f}- AND f.is_final_batch = true- AND fdgs.job_state = 'succeeded'- AND EXISTS (- SELECT 1- FROM {BATCH_TABLE} h- WHERE h.run_uuid = f.run_uuid- AND h.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND h.batch_index = 0- AND h.is_final_batch = false- AND h.is_resume = false- AND (h.sync_type = 'full_refresh' OR (h.sync_type = 'incremental' AND h.is_first_ever_sync))- )- LIMIT 1- """,- {"team_id": state.team_id, "schema_id": str(state.schema_id)},- ).fetchone()- if done is None:- return-- flipped = sink_state.mark_resync_completed(state.id)- if flipped:- logger.info("duckgres_backfill_resync_completed", schema_id=str(state.schema_id))---def _emit_state_gauge() -> None:- stats = sink_state.get_sink_state_gauge_stats(failing_threshold=FAILING_THRESHOLD)- for state in DuckgresSinkState:- BACKFILL_SCHEMAS_GAUGE.labels(state=state.value).set(stats.counts.get(state, 0))-- # Derived from the state table, not batches, so a stuck schema stays visible- # past queue retention — the durable "backfill owed since" high-watermark.- STUCK_BACKFILL_GAUGE.set(stats.failing_count)- oldest = stats.oldest_failure_at- STUCK_BACKFILL_OLDEST_AGE_GAUGE.set((timezone.now() - oldest).total_seconds() if oldest else 0.0)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.pydeleted file mode 100644index a85ec33340bb..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py+++ /dev/null@@ -1,251 +0,0 @@-"""Queue-side writes for the duckgres backfill.--Everything here is idempotent so the reconciler can replay any step after a-crash: pre-apply markers upsert by their natural key, status inserts guard on-the latest-status view, and chunk enqueue keys on (run_uuid, batch_index).-"""--from __future__ import annotations--import uuid-from typing import Any--import psycopg-import structlog--from products.warehouse_sources.backend.models import ExternalDataSchema-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (- BackfillChunk,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (- LIVE_BATCH_SQL_PREDICATE,- build_backfill_metadata,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- BATCH_TABLE,- PARTITION_PRUNING_INTERVAL,- STATUS_TABLE as DELTA_STATUS_TABLE,-)--logger = structlog.get_logger(__name__)--BACKFILL_JOB_ID = "duckgres-backfill"--# Session advisory-lock namespace that serializes enqueue_chunks per run_uuid.-# Distinct from the batch-claim lock namespace (0x44475300) so the two never-# conflict: (run_uuid, batch_index) has no DB uniqueness guard, so without this-# two pods replaying _reconcile_one for the same run could both pass the-# existing-index check and insert duplicate chunk rows.-BACKFILL_ENQUEUE_LOCK_NAMESPACE = 0x44475301 # "DGS\x01"--# Structured kinds stamped into duckgres status error_response by this module's-# writers (the reconciler dispatches on these, never on message prose).-KIND_COVERED_BY_SNAPSHOT = "covered_by_backfill_snapshot"-KIND_RETIRED_BY_REPLAN = "retired_by_backfill_replan"--REASON_COVERED_BY_SNAPSHOT = "covered by duckgres backfill snapshot"-REASON_RETIRED_BY_REPLAN = "retired by backfill replan"---def backfill_run_uuid(schema_id: str, snapshot_version: int) -> str:- """Unique per planning attempt: the generation nonce guarantees a replan at- an unadvanced Delta version still gets a fresh, claimable run."""- return f"{BACKFILL_JOB_ID}-{schema_id}-v{snapshot_version}-g{uuid.uuid4().hex[:8]}"---def preapply_covered_batches(- conn: psycopg.Connection[Any],- *,- team_id: int,- schema_id: str,- covered_batches: list[tuple[str, int]],- reason: str,-) -> int:- """Mark snapshot-contained batches as already applied — skip, never fail.-- Containment proof is per BATCH: the planner reads the pinned Delta snapshot's- commit metadata and passes every (run_uuid, batch_index) whose commit version- is <= the snapshot version. Queue timestamps are deliberately not used here;- they can race the Delta snapshot read.-- "Applied" is the correct verb (not "failed"): a failed batch poisons its- whole run via the failed-run exclusion, which would drop a mid-flight run's- later, post-snapshot batches. Pre-applying instead composes with every- existing gate: the batch stops being claimable (succeeded status), and its- siblings' head-of-line check sees it applied (apply marker).-- Idempotent: the marker upserts on its natural key and the status insert- guards on the latest-status view. Final markers are skipped (they never- carry apply rows; their no-op pass after PRIMED converges them).- """- if not covered_batches:- return 0-- covered_batch_rows = [- {"run_uuid": run_uuid, "batch_index": batch_index} for run_uuid, batch_index in covered_batches- ]- covered_scope = f"""- FROM {BATCH_TABLE} b- JOIN (- SELECT *- FROM jsonb_to_recordset(%(covered_batches)s::jsonb)- AS covered(run_uuid text, batch_index int)- ) covered- ON covered.run_uuid = b.run_uuid- AND covered.batch_index = b.batch_index- JOIN v_latest_source_batch_status ds ON b.id = ds.batch_id- LEFT JOIN v_latest_source_batch_duckgres_status dgs ON b.id = dgs.batch_id- WHERE b.team_id = %(team_id)s- AND b.schema_id = %(schema_id)s- AND b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND {LIVE_BATCH_SQL_PREDICATE}- AND b.is_final_batch = false- AND ds.job_state = 'succeeded'- AND (dgs.batch_id IS NULL OR dgs.job_state = 'waiting_retry')- """- params = {- "team_id": team_id,- "schema_id": schema_id,- "covered_batches": psycopg.types.json.Jsonb(covered_batch_rows),- "reason": reason,- "kind": KIND_COVERED_BY_SNAPSHOT,- }- with conn.transaction():- cursor = conn.execute(- f"""- INSERT INTO sourcebatchduckgresapply (team_id, schema_id, run_uuid, batch_index, batch_id, row_count)- SELECT b.team_id, b.schema_id, b.run_uuid, b.batch_index, b.id, b.row_count- {covered_scope}- ON CONFLICT (team_id, schema_id, run_uuid, batch_index) DO NOTHING- """,- params,- )- conn.execute(- f"""- INSERT INTO sourcebatchduckgresstatus (batch_id, job_state, attempt, error_response)- SELECT b.id, 'succeeded', 0, jsonb_build_object('note', %(reason)s::text, 'kind', %(kind)s::text)- {covered_scope}- """,- params,- )- return cursor.rowcount or 0---def enqueue_chunks(- conn: psycopg.Connection[Any],- schema: ExternalDataSchema,- run_uuid: str,- chunks: list[BackfillChunk],-) -> int:- """Insert the synthetic run, idempotently by (run_uuid, batch_index).-- Each batch row and its pre-succeeded Delta status row commit in ONE- transaction: a synthetic row visible without 'succeeded' status would be- claimed by the Delta consumer and loaded into the Delta table.-- (run_uuid, batch_index) has no DB uniqueness guard, so a bare- read-existing-then-insert races: two pods replaying _reconcile_one for the- same run could both miss a chunk in ``existing`` and insert it twice. A- session advisory lock keyed on run_uuid serializes enqueue across pods, so- the later pod reads a complete ``existing`` set and inserts nothing.- """- inserted = 0- # The advisory lock is session-scoped and previously unbounded: a pod dying- # without FIN leaves the server session (and the lock) alive for hours, and- # every other pod's reconciler replay then blocks here — inline in the- # consumer's fetch path — halting all duckgres claiming fleet-wide. Bound- # the wait; a timeout skips the replay for this tick and the next tick- # retries after the dead session is reaped.- conn.execute("SET lock_timeout = '10s'")- try:- conn.execute(- "SELECT pg_advisory_lock(%s, hashtext(%s))",- [BACKFILL_ENQUEUE_LOCK_NAMESPACE, run_uuid],- )- except psycopg.errors.LockNotAvailable:- conn.execute("RESET lock_timeout")- logger.warning("duckgres_backfill_enqueue_lock_timeout", run_uuid=run_uuid)- return 0- try:- existing = {- row[0]- for row in conn.execute(f"SELECT batch_index FROM {BATCH_TABLE} WHERE run_uuid = %s", [run_uuid]).fetchall()- }- for chunk in chunks:- if chunk.index in existing:- continue- batch_id = str(uuid.uuid4())- with conn.transaction():- conn.execute(- f"""- INSERT INTO {BATCH_TABLE} (- id, team_id, schema_id, source_id, job_id, run_uuid,- batch_index, s3_path, row_count, byte_size, is_final_batch,- total_batches, total_rows, sync_type, cumulative_row_count,- resource_name, is_resume, is_first_ever_sync, metadata,- latest_state, latest_attempt, state_changed_at- ) VALUES (- %(id)s, %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,- %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, false,- %(total_batches)s, NULL, 'full_refresh', 0,- %(resource_name)s, true, false, %(metadata)s,- 'succeeded', 1, now()- )- """,- {- "id": batch_id,- "team_id": schema.team_id,- "schema_id": str(schema.id),- "source_id": str(schema.source_id),- "job_id": BACKFILL_JOB_ID,- "run_uuid": run_uuid,- "batch_index": chunk.index,- "s3_path": chunk.paths[0],- "row_count": chunk.row_count,- "byte_size": chunk.byte_size,- "total_batches": len(chunks),- "resource_name": schema.name,- "metadata": psycopg.types.json.Jsonb(- build_backfill_metadata(chunk_paths=chunk.paths, chunk_count=len(chunks))- ),- },- )- conn.execute(- f"INSERT INTO {DELTA_STATUS_TABLE} (batch_id, job_state, attempt) VALUES (%s, 'succeeded', 1)",- [batch_id],- )- inserted += 1- finally:- conn.execute(- "SELECT pg_advisory_unlock(%s, hashtext(%s))",- [BACKFILL_ENQUEUE_LOCK_NAMESPACE, run_uuid],- )- conn.execute("RESET lock_timeout")- return inserted---def retire_backfill_run(conn: psycopg.Connection[Any], *, run_uuid: str) -> None:- """Terminally fail a backfill run's unapplied chunks (operator replan).-- Failing (not pre-applying) is correct HERE: a replanned run's chunks must- never execute, and the failed-run exclusion is exactly that. The kind is- deliberately distinct from a live-replace supersession so the reconciler- can never mistake a replan for a completed refresh.- """- conn.execute(- f"""- INSERT INTO sourcebatchduckgresstatus (batch_id, job_state, attempt, error_response)- -- jsonb_build_object is VARIADIC "any", so bare placeholders are- -- type-indeterminate to Postgres ("could not determine data type of- -- parameter"); cast the string args explicitly.- SELECT b.id, 'failed', 0, jsonb_build_object('error', %(reason)s::text, 'kind', %(kind)s::text)- FROM {BATCH_TABLE} b- LEFT JOIN sourcebatchduckgresapply a- ON a.team_id = b.team_id AND a.schema_id = b.schema_id- AND a.run_uuid = b.run_uuid AND a.batch_index = b.batch_index- WHERE b.run_uuid = %(run_uuid)s- AND b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND a.id IS NULL- """,- {"run_uuid": run_uuid, "reason": REASON_RETIRED_BY_REPLAN, "kind": KIND_RETIRED_BY_REPLAN},- )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.pydeleted file mode 100644index 447d63c93ea1..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py+++ /dev/null@@ -1,265 +0,0 @@-"""Delta snapshot resolution and chunk planning for the duckgres backfill.--Pure read-side: no queue or app-DB writes live here. Given a schema (and-optionally a pinned version), produce the chunk plan — groups of the Delta-table's own live parquet files bounded by bytes and file count.-"""--from __future__ import annotations--import json-import threading-from collections import OrderedDict-from dataclasses import dataclass-from typing import Any-from urllib.parse import unquote--from django.conf import settings--from products.data_warehouse.backend.facade.api import delta_proxy_storage_options-from products.warehouse_sources.backend.models import ExternalDataSchema-from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention--CHUNK_TARGET_BYTES = 1024**3 # ~1 GiB of parquet per chunk statement-MAX_FILES_PER_CHUNK = 512 # bound the read_parquet([...]) literal list---class BackfillUnsupportedError(Exception):- """The Delta table cannot be backfilled by this planner (parks NEEDS_RESYNC)."""---@dataclass(frozen=True)-class BackfillChunk:- index: int- paths: list[str]- byte_size: int- row_count: int---@dataclass(frozen=True)-class BackfillSnapshotPlan:- snapshot_version: int- chunks: list[BackfillChunk]- covered_batches: list[tuple[str, int]]---def delta_table_uri(schema: ExternalDataSchema) -> str:- return f"{settings.BUCKET_URL}/{schema.folder_path()}/{_delta_table_folder(schema)}"---def _delta_table_folder(schema: ExternalDataSchema) -> str:- """The Delta table's own folder segment, as the loader actually wrote it.-- The loader names the folder after the DLT resource (the unqualified table- name), so it diverges from schema.normalized_name for schema-qualified- sources: Postgres "public.foo" normalizes to "public_foo", but the Delta- folder is "foo". Reading normalized_name here points the backfill at a- prefix with no _delta_log (surfaces as "No files in log segment"). The- catalog table's url_pattern is the authoritative location — it is what the- query engine reads — so take the leaf from there, and fall back to- normalized_name only when no table row exists yet (nothing to backfill).-- url_pattern is a user-writable field, so the leaf is normalized through the- same convention the writer used to produce it. This is a no-op for every- legitimate folder (they are already normalize_identifier output) and strips- any injected separators so the leaf can never escape the schema's own prefix.- """- table = schema.table- if table and table.url_pattern:- segments = [seg for seg in table.url_pattern.rstrip("/").split("/") if seg and seg not in ("*", "**")]- if segments:- return NamingConvention.normalize_identifier(segments[-1])- return schema.normalized_name---def _delta_storage_options() -> dict[str, str]:- """Storage options for metadata-only Delta log reads from the consumer pod.-- Production credentials come from the pod's ambient AWS chain (IRSA/env), which- deltalake's object_store resolves itself. The only production option is the scoped- proxy bypass for the warehouse bucket. Local development uses MinIO endpoint and keys.- (products.managed_warehouse.backend.storage.get_deltalake_storage_options is NOT usable- here: it requires DuckLake RDS env that consumer pods do not carry.)- """- if settings.USE_LOCAL_SETUP:- return {- "AWS_ACCESS_KEY_ID": settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,- "AWS_SECRET_ACCESS_KEY": settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,- "AWS_ENDPOINT_URL": settings.OBJECT_STORAGE_ENDPOINT,- "AWS_ALLOW_HTTP": "true",- "AWS_REGION": "us-east-1",- }- return dict(delta_proxy_storage_options())---def resolve_snapshot_chunks(schema: ExternalDataSchema, version: int | None = None) -> tuple[int, list[BackfillChunk]]:- plan = resolve_snapshot_plan(schema, version=version)- return plan.snapshot_version, plan.chunks---def resolve_snapshot_plan(schema: ExternalDataSchema, version: int | None = None) -> BackfillSnapshotPlan:- uri = delta_table_uri(schema)- if version is None:- # No pinned version to cache against — this is the initial plan, reading- # whatever HEAD currently is, which is not a stable cache key.- return _resolve_snapshot_plan(uri, version)- return _resolve_pinned_snapshot_plan(uri, version)---# A cached plan holds every live parquet path and commit key for its table, so-# entry *size* scales with table size — an entry-count cap alone doesn't bound-# memory. Weigh entries by that count and cap the total instead: a plan over-# budget on its own is simply never cached (recomputed every call, same as-# before this cache existed), so one huge table can't make the cache retain an-# unbounded amount indefinitely.-_PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT = 50_000--_pinned_snapshot_plan_cache: OrderedDict[tuple[str, int], tuple[BackfillSnapshotPlan, int]] = OrderedDict()-_pinned_snapshot_plan_cache_weight = 0-_pinned_snapshot_plan_cache_lock = threading.Lock()---def _plan_weight(plan: BackfillSnapshotPlan) -> int:- return sum(len(chunk.paths) for chunk in plan.chunks) + len(plan.covered_batches)---def _resolve_pinned_snapshot_plan(uri: str, version: int) -> BackfillSnapshotPlan:- """Cached for already-committed (pinned) versions only.-- A commit at or before an already-resolved version never changes, but- deltalake's history() has no checkpoint shortcut — it walks the- _delta_log from genesis one commit at a time. The reconciler calls- resolve_snapshot_plan with the same pinned version on every ~30s tick- until a backfill finishes draining its queue, so without this cache a- large table (tens of thousands of commits) gets its entire commit log- re-read from S3 on every pass, which can trip S3 rate limiting.- """- global _pinned_snapshot_plan_cache_weight-- key = (uri, version)- with _pinned_snapshot_plan_cache_lock:- cached = _pinned_snapshot_plan_cache.get(key)- if cached is not None:- _pinned_snapshot_plan_cache.move_to_end(key)- return cached[0]-- plan = _resolve_snapshot_plan(uri, version)- weight = _plan_weight(plan)-- with _pinned_snapshot_plan_cache_lock:- while (- _pinned_snapshot_plan_cache- and _pinned_snapshot_plan_cache_weight + weight > _PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT- ):- _, (_, evicted_weight) = _pinned_snapshot_plan_cache.popitem(last=False)- _pinned_snapshot_plan_cache_weight -= evicted_weight- if weight <= _PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT:- _pinned_snapshot_plan_cache[key] = (plan, weight)- _pinned_snapshot_plan_cache_weight += weight- return plan---def _resolve_snapshot_plan(uri: str, version: int | None) -> BackfillSnapshotPlan:- from deltalake import DeltaTable-- dt = DeltaTable(uri, version=version, storage_options=_delta_storage_options())- resolved_version = dt.version()-- if _has_deletion_vectors(dt):- # deltalake 1.4.0 cannot stream DV tables (to_pyarrow_dataset rejects- # the reader feature), and reading the add files directly would serve- # deleted rows. Park the schema; a full-refresh resync heals it.- raise BackfillUnsupportedError(- "Delta table has the deletionVectors reader feature; backfill requires a full resync"- )-- adds = dt.get_add_actions(flatten=True)- paths = adds.column("path").to_pylist()- sizes = adds.column("size_bytes").to_pylist()- counts: list[int]- try:- counts = [int(c) if c is not None else 0 for c in adds.column("num_records").to_pylist()]- except KeyError:- counts = [0] * len(paths)-- files = []- for p, size, rows in zip(paths, sizes, counts):- # Add-action paths are percent-encoded relative paths (or, rarely,- # absolute URIs). Decode so read_parquet sees the real object key.- decoded = unquote(p)- full = decoded if decoded.startswith(("s3://", "s3a://")) else f"{uri.rstrip('/')}/{decoded}"- files.append((full, size or 0, rows or 0))- return BackfillSnapshotPlan(- snapshot_version=resolved_version,- chunks=_group_files_into_chunks(files),- covered_batches=_committed_batch_keys(dt, snapshot_version=resolved_version),- )---def _has_deletion_vectors(dt: Any) -> bool:- """Conservative: a DV-enabled table parks even if no DV is currently active —- re-deriving per-file DV state is not worth the risk of serving deleted rows."""- try:- protocol = dt.protocol()- features = list(protocol.reader_features or [])- return "deletionVectors" in features- except Exception:- return True # unknown protocol shape: park, never lie---def _committed_batch_keys(dt: Any, *, snapshot_version: int) -> list[tuple[str, int]]:- """Return live v3 batch keys committed at or before the pinned snapshot.-- Delta commits are the only exact boundary for snapshot containment. Queue- timestamps can race the snapshot read, but a commit with version <= the- pinned version is necessarily represented in the files this backfill reads.- """- keys: list[tuple[str, int]] = []- for commit in dt.history():- commit_version = commit.get("version")- if isinstance(commit_version, int) and commit_version > snapshot_version:- continue-- metadata = _commit_metadata(commit)- run_uuid = metadata.get("run_uuid")- batch_index = metadata.get("batch_index")- if run_uuid is None or batch_index is None:- continue- try:- keys.append((str(run_uuid), int(batch_index)))- except (TypeError, ValueError):- continue- return keys---def _commit_metadata(commit: dict[str, Any]) -> dict[str, Any]:- metadata: dict[str, Any] = dict(commit)- raw = commit.get("userMetadata")- if isinstance(raw, str):- try:- nested = json.loads(raw)- except (json.JSONDecodeError, ValueError):- nested = {}- elif isinstance(raw, dict):- nested = raw- else:- nested = {}- metadata.update(nested)- return metadata---def _group_files_into_chunks(files: list[tuple[str, int, int]]) -> list[BackfillChunk]:- chunks: list[BackfillChunk] = []- cur_paths: list[str] = []- cur_bytes = 0- cur_rows = 0- for path, size, rows in files:- if cur_paths and (cur_bytes + size > CHUNK_TARGET_BYTES or len(cur_paths) >= MAX_FILES_PER_CHUNK):- chunks.append(BackfillChunk(len(chunks), cur_paths, cur_bytes, cur_rows))- cur_paths, cur_bytes, cur_rows = [], 0, 0- cur_paths.append(path)- cur_bytes += size- cur_rows += rows- if cur_paths:- chunks.append(BackfillChunk(len(chunks), cur_paths, cur_bytes, cur_rows))- return chunksdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/batch_kind.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/batch_kind.pydeleted file mode 100644index 1a6c71b8e8ef..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/batch_kind.py+++ /dev/null@@ -1,44 +0,0 @@-"""Canonical definition of "what kind of batch is this?" for the duckgres sink.--Two kinds exist: LIVE batches produced by the v3 sync pipeline, and synthetic-DUCKGRES_BACKFILL batches enqueued by the backfill planner. The discriminator-travels in batch metadata (the queue schema predates the distinction; a typed-``kind`` column on sourcebatch is the planned follow-up migration). Every-consumer of the distinction — queue SQL, processor dispatch, planner enqueue —-derives it from THIS module so the convention has exactly one definition per-language (one Python predicate, one SQL fragment).-"""--from __future__ import annotations--from typing import Any--BACKFILL_METADATA_KEY = "duckgres_backfill"--# SQL twin of is_backfill_metadata, for queries aliasing sourcebatch as ``b``.-LIVE_BATCH_SQL_PREDICATE = f"(b.metadata->>'{BACKFILL_METADATA_KEY}') IS NULL"-BACKFILL_BATCH_SQL_PREDICATE = f"(b.metadata->>'{BACKFILL_METADATA_KEY}') IS NOT NULL"---def is_backfill_metadata(metadata: dict[str, Any] | None) -> bool:- return bool(metadata and metadata.get(BACKFILL_METADATA_KEY))---def build_backfill_metadata(*, chunk_paths: list[str], chunk_count: int) -> dict[str, Any]:- """The only shape backfill batch metadata is ever written in."""- return {- BACKFILL_METADATA_KEY: True,- "chunk_paths": chunk_paths,- "chunk_count": chunk_count,- }---def backfill_chunk_paths(metadata: dict[str, Any]) -> list[str]:- paths = metadata.get("chunk_paths")- if not isinstance(paths, list) or not paths:- raise ValueError("backfill batch has no chunk_paths metadata")- return [str(p) for p in paths]---def backfill_chunk_count(metadata: dict[str, Any]) -> int:- return int(metadata.get("chunk_count") or 0)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.pydeleted file mode 100644index 73016247e9c8..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ /dev/null@@ -1,689 +0,0 @@-from __future__ import annotations--import time-from collections.abc import Callable-from datetime import datetime-from typing import Any--from django.db import close_old_connections--import psycopg-import structlog-from asgiref.sync import sync_to_async-from prometheus_client import Gauge--from posthog.exceptions_capture import capture_exception-from posthog.sync import database_sync_to_async_pool--from products.managed_warehouse.backend.facade import sink_state-from products.managed_warehouse.backend.facade.contracts import CPUnavailableError-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (- MAX_ATTEMPTS,- POLL_INTERVAL_SECONDS,- RECOVERY_INTERVAL_SECONDS,- BatchConsumer as SharedBatchConsumer,- BatchConsumerConfig,- OwnershipLostError,- PermanentBatchApplyError,- ProcessBatchFn,- _group_by_key,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (- blocked_schema_ids as compute_blocked_schema_ids,- failing_schema_ids as compute_failing_schema_ids,- mark_schema_diverged,- run_backfill_planner,- sink_eligible_schema_ids as compute_eligible_schema_ids,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (- is_backfill_metadata,-)-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 (- DuckgresBatchQueue,- is_eligibility_query_timeout,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- LEASE_TTL_SECONDS,- PendingBatch,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (- make_consumer_metrics,-)-from products.warehouse_sources_queue.backend.models import SourceBatchDuckgresStatus--logger = structlog.get_logger(__name__)--DuckgresConsumerConfig = BatchConsumerConfig---def _record_live_batch_applied(schema_id: str) -> None:- """Stamp the main-DB sink-state row with the time of this live apply.-- This is what the Data ops Overview tab reports as "last applied to warehouse" —- an event stamped at the moment the work happens, so the web tier never has to- query the warehouse-sources queue DB (which it has no credentials for).- """- close_old_connections()- sink_state.record_live_batch_applied(schema_id)---# How often the fetch path refreshes the enabled-team set and runs the-# supersede sweep + backlog gauges (the poll loop itself runs every ~2s).-ENABLEMENT_REFRESH_SECONDS = 60.0-MAINTENANCE_INTERVAL_SECONDS = 30.0--SINK_ELIGIBLE_BACKLOG = Gauge(- "duckgres_sink_eligible_backlog",- "Delta-succeeded data batches not yet applied to Duckgres (non-failed runs)",- multiprocess_mode="livemax",-)-SINK_OLDEST_ELIGIBLE_AGE_SECONDS = Gauge(- "duckgres_sink_oldest_eligible_age_seconds",- "Age of the oldest delta-succeeded batch the Duckgres sink has not applied. "- "Queue retention permanently drops batches after RETENTION_DAYS — alert well before that.",- multiprocess_mode="livemax",-)-SINK_BLOCKED_BACKLOG = Gauge(- "duckgres_sink_blocked_backlog",- "Delta-succeeded batches held back behind a healthily progressing backfill (pending/in-flight). "- "Excludes failing schemas, so this is the pageable signal: sustained growth is a real throughput problem.",- multiprocess_mode="livemax",-)-SINK_BLOCKED_OLDEST_AGE_SECONDS = Gauge(- "duckgres_sink_blocked_oldest_age_seconds",- "Age of the oldest healthily blocked batch — approaching queue retention means the post-backfill handoff will gap",- multiprocess_mode="livemax",-)-# Visibility-only, deliberately unalerted: hard-blocked schemas are an operator-# remediation queue (durably tracked on the sink state), not a page.-SINK_FAILING_BLOCKED_BACKLOG = Gauge(- "duckgres_sink_failing_blocked_backlog",- "Delta-succeeded batches held back behind a hard-blocked schema (backfill failure streak / needs_resync)",- multiprocess_mode="livemax",-)-SINK_SUPERSEDED_BATCHES_TOTAL = Gauge(- "duckgres_sink_superseded_batches",- "Batches retired because a newer replace-run made their work obsolete (last sweep)",- multiprocess_mode="livemax",-)-SINK_ORGS_AT_BUDGET = Gauge(- "duckgres_sink_orgs_at_budget",- "Orgs whose live group leases have reached their sink_max_concurrency budget. "- "Backlog growing while this is up (and pod utilization is low) means the fleet is "- "budget-limited, not pod-limited — raise the org's budget or duckgres capacity, not replicas.",- multiprocess_mode="livemax",-)---class DuckgresBatchConsumerAdapter:- log_prefix: str = "duckgres"- executing_state: str = SourceBatchDuckgresStatus.State.EXECUTING.value- succeeded_state: str = SourceBatchDuckgresStatus.State.SUCCEEDED.value- waiting_retry_state: str = SourceBatchDuckgresStatus.State.WAITING_RETRY.value- # Lease ownership is token-based, so groups get their own connections and- # the poll loop keeps claiming while groups run (no per-cycle barrier).- per_group_connections: bool = True- # A skip means "already applied": the engine's succeeded record is what- # retires the batch (terminal retirement raises OwnershipLostError instead).- record_skip_as_success: bool = True-- def __init__(self, lease_ttl_seconds: int = LEASE_TTL_SECONDS) -> None:- # TTL for verify_advisory_lock's boundary renewals (the consumer's- # configured group-lease TTL).- self._lease_ttl_seconds = lease_ttl_seconds- self._team_ids: list[int] | None = None- # (team_id, org_id, sink_max_concurrency) rows for enabled teams —- # refreshed with the team set, passed into the claim so the per-org- # group budget is enforced fleet-wide. Empty in dev (no caps).- self._team_org_budgets: list[tuple[int, str, int]] = []- self._team_ids_fetched_at: float | None = None- self._last_maintenance_at = 0.0- # None = not yet computed; the fetch claims nothing until the first- # successful planner pass so unprimed schemas can't sneak live batches in.- self._blocked_schema_ids: list[str] | None = None- # Subset of the blocked set whose backfill is hard-blocked (failure- # streak / needs_resync); their batches report on the unalerted failing- # gauge instead of the pageable blocked gauges.- self._failing_schema_ids: list[str] | None = None- # Allow-list of v3-enabled schema ids (prod only). None = not yet computed- # (fetch claims nothing) in prod; stays None in dev where team_ids is None- # and the sink is intentionally ungated.- self._eligible_schema_ids: list[str] | None = None-- async def _enabled_team_ids(self) -> list[int] | None:- """Cached duckgres-enabled team set; keeps the previous set on app-DB errors."""- now = time.monotonic()- if self._team_ids_fetched_at is not None and now - self._team_ids_fetched_at < ENABLEMENT_REFRESH_SECONDS:- return self._team_ids- try:- first_resolution = self._team_ids_fetched_at is None- previous = self._team_ids- # database_sync_to_async_pool (not a bare sync_to_async) so a connection killed by- # the DB/proxy since the last refresh gets closed and reopened before this query,- # instead of surfacing as "the connection is closed" OperationalErrors.- enablement = await database_sync_to_async_pool(duckgres_sink_enablement)()- self._team_ids = None if enablement is None else enablement.team_ids- self._team_org_budgets = [] if enablement is None else enablement.team_org_budgets- self._team_ids_fetched_at = now- if first_resolution or self._team_ids != previous:- # Only on the first resolution or an actual change — the refresh- # itself runs every ~60s and would otherwise spam.- logger.info(- "duckgres_sink_enabled_teams_resolved",- first_resolution=first_resolution,- team_count=None if self._team_ids is None else len(self._team_ids),- org_count=len({org_id for _, org_id, _ in self._team_org_budgets}),- )- except CPUnavailableError:- # A brief control-plane blip is expected and self-healing: we keep the- # previously cached team set so the sink keeps serving. Log-only — this- # is not an error-tracking-worthy failure. Advance the refresh clock on- # the way out (below) so we don't re-poll the struggling control plane- # every ~2s cycle across the fleet during an outage.- logger.warning("duckgres_sink_enablement_control_plane_unreachable")- if self._team_ids_fetched_at is None:- # Never had a set: claim nothing rather than everything.- self._team_ids = []- self._team_ids_fetched_at = now- except Exception as e:- logger.exception("duckgres_sink_enablement_refresh_failed")- capture_exception(e)- if self._team_ids_fetched_at is None:- # Never had a set: claim nothing rather than everything.- self._team_ids = []- self._team_ids_fetched_at = now- return self._team_ids-- async def _run_maintenance(self, conn: psycopg.AsyncConnection[Any], team_ids: list[int] | None) -> None:- """Supersede obsolete runs and refresh the sink lag gauges (every ~30s)."""- now = time.monotonic()- if now - self._last_maintenance_at < MAINTENANCE_INTERVAL_SECONDS:- return- self._last_maintenance_at = now-- try:- # Eligibility-CTE queries scan the queue DB over the partition-pruning- # window per enabled team; they are statement-timeout bounded (see- # jobs_db). A timeout or transient queue-DB error must not wedge or- # crash the poll loop — skip this tick and retry on the next one.- superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn, team_ids=team_ids)- SINK_SUPERSEDED_BATCHES_TOTAL.set(superseded)- if superseded:- logger.info("duckgres_superseded_obsolete_batches", count=superseded)-- 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(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- )- SINK_ORGS_AT_BUDGET.set(orgs_at_budget)- except Exception as e:- if is_eligibility_query_timeout(e):- # Expected under a slow/loaded queue DB — the eligibility-CTE- # queries are timeout-bounded specifically so this fails fast- # and the next tick just retries; not worth an error-tracking report.- logger.warning("duckgres_sink_maintenance_query_timed_out")- else:- logger.exception("duckgres_sink_maintenance_query_failed")- capture_exception(e)- return-- block_list_was_unset = self._blocked_schema_ids is None- try:- # Backfill planner: bootstrap/plan/reconcile schema priming, then- # refresh the live-batch block list it derives from.- await sync_to_async(run_backfill_planner, thread_sensitive=False)(team_ids)- self._blocked_schema_ids = await sync_to_async(compute_blocked_schema_ids, thread_sensitive=False)(team_ids)- self._failing_schema_ids = await sync_to_async(compute_failing_schema_ids, thread_sensitive=False)(team_ids)- # v3 allow-list: prod only. In dev (team_ids None) the sink stays- # ungated, matching the team filter. Kept in the planner try so a- # transient app-DB/flag blip leaves the previous allow-list intact.- if team_ids is not None:- self._eligible_schema_ids = await sync_to_async(compute_eligible_schema_ids, thread_sensitive=False)(- team_ids- )- if block_list_was_unset:- # First successful planner pass: the sink can now claim live- # batches (fetch returns [] until this happens).- logger.info(- "duckgres_backfill_block_list_ready",- blocked_schema_count=len(self._blocked_schema_ids),- )- except Exception as e:- # An app-DB blip must not crash the poll loop; keep the previous- # block list (or keep claiming nothing if we never had one).- logger.exception("duckgres_backfill_planner_failed")- capture_exception(e)-- # Heartbeat: confirms the ~30s maintenance pass (enablement set, supersede- # sweep, planner) actually ran. Bounded to one line per maintenance tick.- logger.info(- "duckgres_maintenance_ran",- team_count=None if team_ids is None else len(team_ids),- 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),- eligible_schema_count=None if self._eligible_schema_ids is None else len(self._eligible_schema_ids),- )-- async def fetch_and_lock(- self,- conn: psycopg.AsyncConnection[Any],- *,- limit: int,- retry_backoff_base_seconds: int,- owner_token: str,- lease_ttl_seconds: int,- max_groups: int | None = None,- exclude_groups: list[tuple[int, str]] | None = None,- ) -> list[PendingBatch]:- team_ids = await self._enabled_team_ids()- if team_ids is not None and not team_ids:- return []-- await self._run_maintenance(conn, team_ids)-- if self._blocked_schema_ids is None:- # Planner has not succeeded yet: claiming live batches now could- # write partial history for unprimed schemas. Wait for it.- return []-- if team_ids is not None and self._eligible_schema_ids is None:- # Prod: the v3 allow-list has not been computed yet. Claim nothing- # rather than risk applying batches for non-v3 source types. (Dev,- # team_ids None, is intentionally ungated.)- return []-- return await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn,- owner_token=owner_token,- limit=limit,- retry_backoff_base_seconds=retry_backoff_base_seconds,- team_ids=team_ids,- blocked_schema_ids=self._blocked_schema_ids,- eligible_schema_ids=self._eligible_schema_ids,- lease_ttl_seconds=lease_ttl_seconds,- max_groups=max_groups,- exclude_groups=exclude_groups,- team_org_budgets=self._team_org_budgets,- )-- async def unlock(- self,- conn: psycopg.AsyncConnection[Any],- *,- batches: list[PendingBatch],- owner_token: str,- ) -> None:- await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches, owner_token=owner_token)-- async def release_all_owned(- self,- conn: psycopg.AsyncConnection[Any],- *,- owner_token: str,- ) -> None:- await DuckgresBatchQueue.release_all_owned_leases(conn, owner_token=owner_token)-- async def update_status(- self,- conn: psycopg.AsyncConnection[Any],- *,- batch_id: str,- job_state: str,- attempt: int,- error_response: dict[str, Any] | None = None,- batch_created_at: datetime | None = None, # delta-sink denormalization only; unused here- expected_state_changed_at: datetime | None = None, # delta-sink recovery CAS only; unused here- ) -> None:- # Invariant: never write ANY status over a terminal 'failed' — statuses- # are latest-row-wins, so an unconditional write would un-retire a batch- # a supersede/replan/fail_run retired mid-claim. A blocked insert means- # abort the group with no write (see update_status_unless_failed).- inserted = await DuckgresBatchQueue.update_status_unless_failed(- conn,- batch_id=batch_id,- job_state=job_state,- attempt=attempt,- error_response=error_response,- )- if not inserted:- raise OwnershipLostError(f"batch {batch_id} was terminally retired while claimed")-- async def fail_run(- self,- conn: psycopg.AsyncConnection[Any],- *,- batch: PendingBatch,- reason: str,- ) -> None:- # Contract: fail_run must not raise (see BatchConsumerAdapter docstring).- try:- await DuckgresBatchQueue.fail_run(conn, run_uuid=batch.run_uuid, reason=reason)- except Exception as e:- logger.exception(- "duckgres_fail_run_queue_update_failed",- batch_id=batch.id,- run_uuid=batch.run_uuid,- )- capture_exception(e)-- async def verify_advisory_lock(- self,- conn: psycopg.AsyncConnection[Any],- *,- team_id: int,- schema_id: str,- owner_token: str,- ) -> bool:- # Verify-and-extend: a group of quick chunks can outlive the lease TTL- # without any in-batch heartbeat firing, so the engine's per-batch- # ownership check doubles as the renewal. Returns False exactly when- # the lease was lost — a strict superset of a read-only verify.- return await DuckgresBatchQueue.renew_lease(- conn,- team_id=team_id,- schema_id=schema_id,- owner_token=owner_token,- lease_ttl_seconds=self._lease_ttl_seconds,- )-- async def renew_lease(- self,- conn: psycopg.AsyncConnection[Any],- *,- team_id: int,- schema_id: str,- owner_token: str,- lease_ttl_seconds: int,- ) -> bool:- return await DuckgresBatchQueue.renew_lease(- conn,- team_id=team_id,- schema_id=schema_id,- owner_token=owner_token,- lease_ttl_seconds=lease_ttl_seconds,- )-- async def delete_expired_lease(- self,- conn: psycopg.AsyncConnection[Any],- *,- team_id: int,- schema_id: str,- ) -> None:- # Protocol conformance only: its sole caller is the base engine's recovery- # sweep, which never runs here — DuckgresBatchConsumer overrides _recovery_sweep.- return None-- async def get_stale_executing(- self,- conn: psycopg.AsyncConnection[Any],- *,- grace_seconds: int,- keep_locks: bool = False,- ) -> list[PendingBatch]:- # keep_locks is meaningless for a lease sink (nothing is held), and the- # base engine's keep-then-unlock sweep never runs for this adapter —- # DuckgresBatchConsumer overrides _recovery_sweep.- return await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)-- async def reconcile_failed_runs(- self,- conn: psycopg.AsyncConnection[Any],- *,- grace_seconds: int,- lookback_seconds: int,- limit: int,- ) -> None:- # The Duckgres sink owns no ExternalDataJob lifecycle: a failed Duckgres run- # must not mark the import job failed (Delta already succeeded), so there is- # nothing to reconcile here.- return None-- async def should_process_batch(- self,- conn: psycopg.AsyncConnection[Any],- *,- batch: PendingBatch,- ) -> bool:- # A batch retired mid-claim (supersede/replan) must abort the WHOLE- # group with no status write: applying it could swap stale backfill data- # over a rebuilt table, and its successors in this claim are retired too.- if await DuckgresBatchQueue.is_failed(conn, batch_id=batch.id):- raise OwnershipLostError(f"batch {batch.id} was terminally retired while claimed")- already_applied = await DuckgresBatchQueue.has_applied(conn, batch=batch)- if batch.is_final_batch:- if not already_applied:- raise RuntimeError(f"Final Duckgres marker received before batch {batch.batch_index} was applied")- return False- return not already_applied-- async def after_batch_processed(- self,- conn: psycopg.AsyncConnection[Any],- *,- batch: PendingBatch,- ) -> None:- if batch.is_final_batch:- return- await DuckgresBatchQueue.mark_applied(conn, batch=batch)- if is_backfill_metadata(batch.metadata):- return- try:- await sync_to_async(_record_live_batch_applied, thread_sensitive=False)(batch.schema_id)- except Exception as e:- # The batch is already applied and marked; a failed stamp only leaves the- # Data ops display timestamp behind until the next live apply.- logger.exception("duckgres_live_apply_stamp_failed", schema_id=batch.schema_id)- capture_exception(e)-- def is_retryable_error(self, err: Exception) -> bool:- return not isinstance(err, PermanentBatchApplyError)-- def is_expected_user_error(self, err: Exception) -> bool:- # The duckgres sink applies already-validated Delta batches; it has no expected- # customer-actionable failures of its own to keep out of error tracking.- return False---class DuckgresBatchConsumer(SharedBatchConsumer):- """The shared engine plus the sink's lease-safety overrides, kept out of the- base engine so the delta consumer is unaffected: group-capped claiming- (_fetch_batches), lease release on connect failure (_unlock_group),- ownership-fenced error writes (_handle_batch_failure), and a fenced- recovery sweep with no post-sweep lease release (_recovery_sweep).- """-- def __init__(- self,- config: DuckgresConsumerConfig,- process_batch: ProcessBatchFn,- health_reporter: Callable[[], None] | None = None,- ) -> None:- # The adapter's boundary renewals must use the same TTL as the claim.- adapter = DuckgresBatchConsumerAdapter(lease_ttl_seconds=config.lease_ttl_seconds or LEASE_TTL_SECONDS)- super().__init__(- config=config,- process_batch=process_batch,- adapter=adapter,- health_reporter=health_reporter,- metrics=make_consumer_metrics("duckgres"),- )- self._duckgres_adapter = adapter-- async def _fetch_batches(self, conn: psycopg.AsyncConnection[Any], *, available: int) -> list[PendingBatch]:- return await self._duckgres_adapter.fetch_and_lock(- conn,- # Full poll_limit, not the base _fetch_limit heuristic: one backfill- # run legitimately co-claims many chunks, and max_groups below bounds- # the over-claim by groups — the unit a lease covers.- limit=self._config.poll_limit,- retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,- owner_token=self._owner_token,- lease_ttl_seconds=self._lease_ttl_seconds,- # A leased-but-unstarted group is renewed by every poll and stays- # dark to other pods, so never lease beyond our free slots.- max_groups=available,- # In-flight groups can't start again; re-claiming them starves- # other schemas of the budget.- exclude_groups=list(self._in_flight),- )-- async def _unlock_group(- self,- group_conn: psycopg.AsyncConnection[Any] | None,- batches: list[PendingBatch],- *,- team_id: int,- schema_id: str,- ) -> None:- if group_conn is None:- # Connect failed but the leases were claimed at fetch time. Release- # them via the poll connection (release is token-scoped) or this- # pod pins the groups — every poll renews its own leases.- try:- fallback_conn = await self._ensure_poll_conn()- except Exception:- return # queue DB fully unreachable; lease TTL is the backstop- try:- await self._duckgres_adapter.unlock(fallback_conn, batches=batches, owner_token=self._owner_token)- except Exception as e:- logger.exception(- self._event("unlock_for_batches_failed"),- team_id=team_id,- external_data_schema_id=schema_id,- )- capture_exception(e)- return- await super()._unlock_group(group_conn, batches, team_id=team_id, schema_id=schema_id)-- async def _handle_batch_failure(- self,- batch: PendingBatch,- attempt: int,- err: Exception,- *,- lock_conn: psycopg.AsyncConnection[Any] | None,- status_conn: psycopg.AsyncConnection[Any],- ) -> None:- # A worker can outlive its lease mid-batch; a stale writer must not- # stamp waiting_retry — or fail the run — over the new owner's- # lifecycle. Raising abandons the group with no status write.- try:- await self._verify_ownership(lock_conn, batch)- except OwnershipLostError:- logger.warning(- self._event("ownership_lost_suppressing_error_status"),- batch_id=batch.id,- run_uuid=batch.run_uuid,- error=str(err)[:500],- )- raise- await super()._handle_batch_failure(batch, attempt, err, lock_conn=lock_conn, status_conn=status_conn)- if (attempt >= self._config.max_attempts or isinstance(err, PermanentBatchApplyError)) and not (- is_backfill_metadata(batch.metadata)- ):- # Terminal failure of a LIVE run: earlier batches applied, the rest- # never will — the duckgres table is durably behind Delta. Park the- # schema so the gap stops compounding and shows up as failing- # instead of silently diverging. Backfill chunks are excluded: the- # reconciler escalates those against the BACKFILLING state.- await sync_to_async(mark_schema_diverged, thread_sensitive=False)(- batch.schema_id, run_uuid=batch.run_uuid, error=str(err)- )-- async def _recovery_sweep(self) -> None:- conn = await self._ensure_recovery_conn()-- grace_seconds = self._config.recovery_grace_seconds- assert grace_seconds is not None- # Unlike the base sweep, no claims are released afterwards: the poll- # loop can reclaim a just-requeued group (same owner token) mid-sweep,- # and an owner-scoped delete would strip that fresh lease.- stale = await self._duckgres_adapter.get_stale_executing(conn, grace_seconds=grace_seconds)- if not stale:- self._metrics.recovery_sweeps_total.labels(outcome="clean").inc()- return-- self._metrics.recovery_sweeps_total.labels(outcome="orphans_found").inc()- logger.info(self._event("recovery_sweep_found_stale_batches"), count=len(stale))-- recovery_bound_keys = (- "team_id",- "external_data_schema_id",- "external_data_source_id",- "external_data_job_id",- "run_uuid",- "batch_id",- "resource_name",- "log_source_id",- "attempt",- )- for batch in stale:- structlog.contextvars.bind_contextvars(- team_id=batch.team_id,- external_data_schema_id=batch.schema_id,- external_data_source_id=batch.source_id,- external_data_job_id=batch.job_id,- run_uuid=batch.run_uuid,- batch_id=batch.id,- resource_name=batch.resource_name,- log_source_id=batch.schema_id,- attempt=batch.latest_attempt,- )- try:- # Both writes are fenced inside the insert (still 'executing',- # older than grace, no live lease): a batch that moved since- # the unlocked scan is skipped, never clobbered.- if batch.latest_attempt >= self._config.max_attempts:- failed = await DuckgresBatchQueue.fail_run_if_stale(- conn, batch=batch, reason="max retries exceeded (likely OOM)", grace_seconds=grace_seconds- )- if failed:- logger.warning(- self._event("batch_recovered_max_retries_exceeded"), attempt=batch.latest_attempt- )- self._metrics.runs_failed_total.inc()- else:- logger.info(self._event("batch_recovery_skipped_not_stale"), batch_id=batch.id)- else:- requeued = await DuckgresBatchQueue.requeue_stale_executing(- conn,- batch=batch,- error_response={"error": "executing timed out - pod restart or OOM"},- grace_seconds=grace_seconds,- )- if requeued:- logger.warning(self._event("batch_recovered_for_retry"), attempt=batch.latest_attempt)- else:- logger.info(self._event("batch_recovery_skipped_not_stale"), batch_id=batch.id)- finally:- structlog.contextvars.unbind_contextvars(*recovery_bound_keys)---__all__ = [- "DuckgresBatchConsumer",- "DuckgresBatchConsumerAdapter",- "DuckgresConsumerConfig",- "MAX_ATTEMPTS",- "POLL_INTERVAL_SECONDS",- "RECOVERY_INTERVAL_SECONDS",- "_group_by_key",-]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.pydeleted file mode 100644index 576da98f14e9..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py+++ /dev/null@@ -1,134 +0,0 @@-"""Which teams the Duckgres batch sink is enabled for.--The sink must only claim batches for teams that (a) have a team row in their org's-duckgres control plane and (b) have the rollout feature flag on. The row is created-when the team completes the managed-warehouse enable flow. Claiming anything-else can switch an unregistered team from its legacy team-id schema to a newly-chosen suffix after the sink has already primed it.--The flag also provides mutual exclusion with the legacy-DuckLakeCopyDataImportsWorkflow (full-table copy after each import job): that-workflow skips teams where this flag is enabled, so a table never has two-uncoordinated duckgres writers.-"""--from __future__ import annotations--from dataclasses import dataclass--import structlog-import posthoganalytics--from posthog.exceptions_capture import capture_exception--from products.managed_warehouse.backend.facade.api import (- get_org_id_for_team,- is_dev_mode,- sink_concurrency_by_trusted_organization_ids,-)-from products.managed_warehouse.backend.facade.contracts import CPUnavailableError-from products.managed_warehouse.backend.facade.cp_teams import list_org_team_memberships, list_team_memberships--logger = structlog.get_logger(__name__)--DUCKGRES_BATCH_SINK_FLAG = "duckgres-batch-sink"---def is_duckgres_sink_team_member(team_id: int) -> bool:- """Whether a team has registered its membership in its org's Duckgres warehouse.-- Membership is the team's row in the duckgres control plane; whether the row derives- or pins its schema names is intentionally not part of this check. Raises when the- control plane can't answer — the caller decides how to degrade.- """- organization_id = get_org_id_for_team(team_id)- teams = list_org_team_memberships(organization_id, use_cache=False)- if teams is None:- raise RuntimeError(f"duckgres control plane unreachable resolving sink membership for team {team_id}")- return any(team.team_id == team_id for team in teams)---@dataclass(frozen=True)-class SinkEnablement:- """The sink's per-refresh view of who it serves and how hard it may push.-- ``team_org_budgets`` carries one (team_id, org_id, sink_max_concurrency)- row per enabled team — the queue DB has no teams table, so the claim query- receives this mapping as unnest'd arrays to enforce the per-org group- budget fleet-wide.- """-- team_ids: list[int]- team_org_budgets: list[tuple[int, str, int]]---def duckgres_sink_enablement() -> SinkEnablement | None:- """Enabled teams plus their org's sink concurrency budget, or None for- "no filter, no budgets" (dev mode).-- Runs sync (control-plane read + Django ORM + flag evaluation); call via- sync_to_async from the consumer. Raises on app-DB errors or an unreachable- control plane — the caller keeps its previous cached value so a transient- blip doesn't blind the sink.-- The flag is evaluated only-locally (no per-team network round-trip) with the- org/project group properties supplied inline, matching the data-warehouse-scene- gate and the legacy copy-workflow gate. A team that can't be resolved locally- evaluates falsy and is skipped (safe direction).- """- if is_dev_mode():- return None-- from posthog.models.team.team import Team-- rows = list_team_memberships(use_cache=False)- if rows is None:- raise CPUnavailableError("duckgres control plane unreachable; keeping the previous sink enablement")-- team_info = {- team_id: (str(team_uuid), str(org_id))- for team_id, team_uuid, org_id in Team.objects.filter(id__in=[row.team_id for row in rows]).values_list(- "id", "uuid", "organization_id"- )- }- # Filtered by the app DB's own org ids, never by the control plane's row.organization_id:- # that value is an external, unvalidated string (the CP has test/dev rows keyed by- # human-readable slugs, not UUIDs), and passing it straight into a UUID FK lookup- # raises ValidationError before the org_id match-up below ever runs.- budgets = sink_concurrency_by_trusted_organization_ids({org_id for _, org_id in team_info.values()})-- enabled: list[int] = []- team_org_budgets: list[tuple[int, str, int]] = []- for row in rows:- info = team_info.get(row.team_id)- if info is None:- continue- team_uuid, org_id = info- if org_id.lower() != row.organization_id.lower():- # A control-plane row whose org doesn't match the team's own org is not a- # membership of that team's warehouse — mirror the old server-org join.- continue- sink_max_concurrency = budgets.get(org_id)- if sink_max_concurrency is None:- # No connection row means the sink can't reach the org's server anyway.- continue- try:- if posthoganalytics.feature_enabled(- DUCKGRES_BATCH_SINK_FLAG,- team_uuid,- groups={"organization": org_id, "project": str(row.team_id)},- group_properties={- "organization": {"id": org_id},- "project": {"id": str(row.team_id), "organization_id": org_id},- },- only_evaluate_locally=True,- send_feature_flag_events=False,- ):- enabled.append(row.team_id)- team_org_budgets.append((row.team_id, org_id, sink_max_concurrency))- except Exception as e:- # Flag evaluation failing for one team must not blind the whole sink;- # treat as disabled (safe direction: we skip, never wrongly claim).- logger.exception("duckgres_sink_flag_evaluation_failed", team_id=row.team_id)- capture_exception(e)- return SinkEnablement(team_ids=enabled, team_org_budgets=team_org_budgets)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.pydeleted file mode 100644index a3d3b40c808b..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py+++ /dev/null@@ -1,1310 +0,0 @@-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-from psycopg.rows import dict_row--from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (- LIVE_BATCH_SQL_PREDICATE,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- BATCH_TABLE,- LEASE_TTL_SECONDS,- PARTITION_PRUNING_INTERVAL,- STATUS_TABLE,- ActiveRunRef,- GroupLease,- PendingBatch,- pending_batch_select_columns,- scope_filters,-)--DUCKGRES_STATUS_TABLE = "sourcebatchduckgresstatus"-# Latest-status view, still consumed by the reset_duckgres_failed_runs management-# command. The eligibility queries here use per-batch LATERAL lookups instead.-DUCKGRES_STATUS_VIEW = "v_latest_source_batch_duckgres_status"-DUCKGRES_APPLY_TABLE = "sourcebatchduckgresapply"-# Twin of the delta queue's sourcegrouplease — separate table because both-# consumers process the same (team_id, schema_id) groups and must never contend.-DUCKGRES_LEASE_TABLE = "sourceduckgresgrouplease"---def _latest_status_lateral(status_table: str, batch_alias: str) -> str:- """Latest status row for one batch via the (batch_id, created_at DESC, id DESC)- index. Drop-in for a join to the DISTINCT ON v_latest_source_batch* view, but a- per-batch lookup instead of materializing the whole view. SELECTs `_ls.*` so all- downstream <alias>.<col> references (job_state, created_at, attempt, batch_id) work.-- The created_at bound exists for partition pruning, mirroring the delta queue's- `latest_status_lateral`: both status tables are range-partitioned by created_at,- and without the predicate every probe descends into every partition. A batch's- status rows are always written within the queue's retention horizon, so the- 2x-retention bound cannot hide a live row."""- return (- f"LATERAL (SELECT _ls.* FROM {status_table} _ls "- f"WHERE _ls.batch_id = {batch_alias}.id "- f"AND _ls.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}' "- f"ORDER BY _ls.created_at DESC, _ls.id DESC LIMIT 1)"- )---# Server-side guard for the heavy eligibility-CTE maintenance queries (supersede-# + backlog): each scans PARTITION_PRUNING_INTERVAL of sourcebatch per enabled-# team, and on a high-volume org an unbounded run can saturate the shared queue-# DB. Worse, every ~30s poll starts another, so slow runs stack into many-# concurrent multi-hour scans that also starve the Delta consumer on the same-# DB. Cap each statement so a slow query fails fast and the poll loop retries on-# the next tick instead of wedging. Tune up if a legitimate run needs longer.-ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS = 30_000---def is_eligibility_query_timeout(error: BaseException) -> bool:- """True when ``error`` is a query cancellation, the expected shape of- ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS tripping under a slow/loaded queue DB.- Callers should skip the tick and retry rather than report it as a defect."""- return isinstance(error, psycopg.errors.QueryCanceled)---@asynccontextmanager-async def _statement_timeout(conn: psycopg.AsyncConnection[Any], timeout_ms: int) -> AsyncIterator[None]:- """Bound the wrapped query with a server-side ``statement_timeout``.-- The consumer connection is autocommit, so ``SET LOCAL`` needs an explicit- transaction; it scopes the timeout to this block and resets it on exit.- """- async with conn.transaction():- await conn.execute(f"SET LOCAL statement_timeout = {int(timeout_ms)}")- yield---def duckgres_pending_predicate(delta_alias: str, duckgres_alias: str) -> str:- """A batch is duckgres-pending (still fail-able) when its delta load succeeded- and its latest duckgres status is absent or non-terminal."""- return (- f"({delta_alias}.job_state = 'succeeded' AND "- f"({duckgres_alias}.batch_id IS NULL OR {duckgres_alias}.job_state IN ('waiting_retry', 'executing')))"- )---# Shared between the async consumer path and the sync ops command so both agree-# on what counts as a pending (fail-able) duckgres batch.-DUCKGRES_FAIL_RUN_SQL = f"""- INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- SELECT b.id, 'failed', 0, now(), %(error_response)s, now()- FROM {BATCH_TABLE} b- LEFT JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON true- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b.run_uuid = %(run_uuid)s- AND {duckgres_pending_predicate("ds", "dgs")}-"""---def _stale_executing_sql(scope_sql: str = "") -> str:- """Shared body of the duckgres stale-executing sweep (async consumer and its sync ops twin)."""- return f"""- SELECT- {pending_batch_select_columns("dgs")}- FROM {BATCH_TABLE} b- JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true- LEFT JOIN {DUCKGRES_LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_id- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND dgs.job_state = 'executing'- AND dgs.created_at <= now() - make_interval(secs => %(grace)s)- AND (l.team_id IS NULL OR l.expires_at <= now())- {scope_sql}- ORDER BY b.created_at ASC, b.batch_index ASC- """---# Structured classification key written into duckgres status error_response by-# every terminal-retire writer. Consumers (the backfill reconciler) dispatch on-# this, not on error-message prose.-RETIRE_KIND_SUPERSEDED_BY_REPLACE = "superseded_by_replace"--# A LIVE batch held back because its schema's history is not yet primed.-# Replace-head runs bypass the block: they rebuild the table from scratch, so-# applying them to an unprimed schema is always safe — and they are the-# healing path for schemas parked in NEEDS_RESYNC. Single definition, used by-# both the eligibility gate and the backlog split. Expects %(blocked_schema_ids)s.-BLOCKED_LIVE_BATCH_CONDITION = f"""(- %(blocked_schema_ids)s::varchar[] IS NOT NULL- AND b.schema_id = ANY(%(blocked_schema_ids)s)- AND {LIVE_BATCH_SQL_PREDICATE}- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} bh- WHERE bh.run_uuid = b.run_uuid- AND bh.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND bh.batch_index = 0- AND bh.is_final_batch = false- AND bh.is_resume = false- AND (- bh.sync_type = 'full_refresh'- OR (bh.sync_type = 'incremental' AND bh.is_first_ever_sync)- )- )- )"""---# Shared CTE prelude for eligibility queries (note the trailing comma — callers-# append their own CTEs/SELECT). Callers pass scoped=True when team_ids is a-# concrete list; see _team_scope.-#-# - cand_runs: runs with pending duckgres work — a delta-succeeded batch that is-# not yet duckgres-succeeded. This is the driving set: every run the gate or-# supersede logic compares (candidates incl. final-batch markers, incomplete-# runs, replace_heads, victims) is delta-succeeded-and-not-duckgres-succeeded,-# hence a member of cand_runs. run_starts/failed_runs scope to it so the work-# the queries do is bounded by the live backlog, not the whole 14-day window.-# - run_starts: per-run start time, the total order used for cross-run gating-# (run_uuid tiebreak makes it total even for identical timestamps).-# - failed_runs: runs terminally excluded from the sink — Delta-failed or-# Duckgres-failed (including superseded).-# - incomplete_runs: non-failed runs that still owe unapplied data batches;-# these block newer runs of the same schema (cross-run head-of-line).-def _team_scope(alias: str, *, scoped: bool) -> str:- """Sargable per-team filter for the eligibility scans.-- In prod ``team_ids`` is always the concrete enabled-team list, so emit a- plain ``= ANY(%(team_ids)s)``: the planner prunes to those teams via the- ``(team_id, ...)`` index and never reads a non-enabled team's rows. The old- ``%(team_ids)s IS NULL OR ...`` form existed only to also serve the- dev/ungated case (team_ids IS NULL), but with a bound parameter Postgres- builds a generic plan that cannot fold the NULL check — so it cannot use the- index and seq-scans the whole shared partition window. A single non-enabled- team with a high-volume (e.g. failing) source then dominates that scan and- can push the eligibility/supersede queries past their statement timeout,- even though none of those rows is ever sinked. Unscoped (dev) = match all.- """- return f"AND {alias}.team_id = ANY(%(team_ids)s)" if scoped else ""---def _eligibility_ctes(scoped: bool) -> str:- return f"""cand_runs AS MATERIALIZED (- -- Runs with pending duckgres work: a delta-succeeded batch that is not yet- -- duckgres-succeeded. Superset of every run the gate/supersede compares;- -- run_starts/failed_runs scope to it so the work is bounded by the backlog.- SELECT DISTINCT cb.run_uuid- FROM {BATCH_TABLE} cb- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "cb")} cdgs ON true- WHERE cb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND cb.latest_state = 'succeeded'- {_team_scope("cb", scoped=scoped)}- AND (cdgs.job_state IS NULL OR cdgs.job_state <> 'succeeded')- ),- run_starts AS MATERIALIZED (- SELECT b_rs.run_uuid, min(b_rs.created_at) AS started_at- FROM {BATCH_TABLE} b_rs- WHERE b_rs.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {_team_scope("b_rs", scoped=scoped)}- AND b_rs.run_uuid IN (SELECT run_uuid FROM cand_runs)- GROUP BY b_rs.run_uuid- ),- failed_runs AS MATERIALIZED (- SELECT cr.run_uuid FROM cand_runs cr- WHERE EXISTS (- SELECT 1 FROM {BATCH_TABLE} fb- WHERE fb.run_uuid = cr.run_uuid- AND fb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {_team_scope("fb", scoped=scoped)}- AND fb.latest_state = 'failed'- )- OR EXISTS (- SELECT 1 FROM {BATCH_TABLE} fb- JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "fb")} fdgs ON true- WHERE fb.run_uuid = cr.run_uuid- AND fb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {_team_scope("fb", scoped=scoped)}- AND fdgs.job_state = 'failed'- )- ),- incomplete_runs AS MATERIALIZED (- SELECT old.team_id, old.schema_id, old.run_uuid, rs_ir.started_at,- bool_or((old.metadata->>'duckgres_backfill') IS NOT NULL) AS is_backfill_run- FROM {BATCH_TABLE} old- JOIN run_starts rs_ir ON rs_ir.run_uuid = old.run_uuid- LEFT JOIN {DUCKGRES_APPLY_TABLE} oa- ON oa.team_id = old.team_id- AND oa.schema_id = old.schema_id- AND oa.run_uuid = old.run_uuid- AND oa.batch_index = old.batch_index- WHERE old.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND old.latest_state = 'succeeded'- {_team_scope("old", scoped=scoped)}- AND old.is_final_batch = false- AND oa.id IS NULL- AND old.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)- GROUP BY old.team_id, old.schema_id, old.run_uuid, rs_ir.started_at- ),"""---@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(- conn: psycopg.AsyncConnection[Any],- *,- owner_token: str,- limit: int = 50,- retry_backoff_base_seconds: int = 0,- team_ids: list[int] | None = None,- blocked_schema_ids: list[str] | None = None,- eligible_schema_ids: list[str] | None = None,- lease_ttl_seconds: int = LEASE_TTL_SECONDS,- max_groups: int | None = None,- exclude_groups: list[tuple[int, str]] | None = None,- team_org_budgets: list[tuple[int, str, int]] | None = None,- ) -> list[PendingBatch]:- """Fetch Duckgres-eligible batches whose Delta load has succeeded.-- Duckgres has its own sink state. A source batch is eligible only after the- Delta consumer marks that exact batch row as succeeded.-- Group ownership is a ``sourceduckgresgrouplease`` row per- (team_id, schema_id), claimed-or-renewed in the writable CTE like the- delta queue's lease claim: free, own, or expired leases are claimable;- another pod's live lease drops the group via ``JOIN claimed``. Unlike- the old session advisory lock, an abandoned group simply expires.-- Mixed-version rollout is a single cutover (as with the delta queue's- migration): the claim is pacing, not correctness — concurrent- processors are arbitrated per batch by the duckgres-side apply marker- (``DuckgresBatchAlreadyAppliedError``, a handled no-op). We deliberately- do NOT probe the old advisory lock: a zombie session holding it would- wedge the group indefinitely, the failure mode leases remove.-- ``retry_backoff_base_seconds`` gates the ``waiting_retry`` branch on the age- of the latest Duckgres status row, mirroring the Delta queue's backoff.-- ``team_ids`` restricts eligibility to duckgres-enabled teams (None = no- filter, for tests/dev). The sink must never claim batches for orgs without- a Duckgres deployment — they would burn retries and fail runs for nothing.-- ``blocked_schema_ids`` excludes LIVE batches for schemas whose history is- not yet primed into duckgres (backfill pending/in-flight) — the schema's- own backfill-run batches (metadata.duckgres_backfill) pass through.-- ``eligible_schema_ids`` restricts the claim to schemas whose source is on- warehouse-pipelines-v3 (None = no filter, for tests/dev). This keeps the- sink in lockstep with the v3 routing flag: the shared queue can hold- batches for non-v3 source types (an earlier flag window, or the- flag-independent CDC writer), and without this gate the team-scoped claim- would apply them — including replace-head batches that bypass the unprimed- block. Computed by ``sink_eligible_schema_ids``.-- ``team_org_budgets`` — (team_id, org_id, budget) rows — enforces a- fleet-wide per-org cap on concurrently leased groups. Each in-flight- group holds at most one connection to the org's duckgres server, so the- cap bounds the sink's connection footprint independently of pod count.- Live leases (any owner) count as usage; eligible groups are ranked- oldest-first per org and only the org's remaining slots are claimable,- so a saturated org's groups are SKIPPED — they never head-of-line block- the pod from filling ``max_groups`` with other orgs' work. Soft cap:- overlapping claims from concurrent polls can transiently overshoot by a- group or two for one poll window; the org's duckgres ``max_connections``- is the hard backstop. Teams without a mapping row are uncapped- (None = no caps at all, for tests/dev).-- Intra-run head-of-line: a pending predecessor blocks a batch only when- it cannot be returned AHEAD of it in this same fetch (see the gate's- inline comments) — for LIVE batches and backfill CHUNKS alike, so a- run's consecutive delta-succeeded prefix drains in one claim (bounded- by ``limit``). Co-claimable predecessors sort earlier, land in the same- group, and the group is processed strictly in order with a halt on- first non-success — so chunk 0's CREATE (and a live run's lowest- batch) still applies first, and nothing ever applies past a gap.-- Cross-run head-of-line: a batch is ineligible while an older run (by run- start time) of the same (team_id, schema_id) still has unapplied,- non-failed data batches. Without this, a newer run's batch-0- CREATE OR REPLACE could interleave with an older run's remaining- inserts/merges and permanently mix two runs' rows in the Duckgres table.- Liveness: older runs either complete, fail (max attempts), or are- superseded by ``supersede_replaced_runs`` — all three unblock the gate.- """- scoped = team_ids is not None- async with conn.cursor(row_factory=dict_row) as cur:- await cur.execute(- f"""- WITH {_eligibility_ctes(scoped)}- team_org AS (- -- Enabled-team -> (org, budget) mapping, passed in because the- -- queue DB has no teams table. Empty when no caps apply.- SELECT team_id, org_id, budget- FROM unnest(- %(budget_team_ids)s::bigint[],- %(budget_org_ids)s::varchar[],- %(budget_values)s::int[]- ) AS t(team_id, org_id, budget)- ),- org_usage AS (- -- Fleet-wide in-flight groups per org: every live lease, any- -- owner (including this pod's own in-flight groups, which the- -- candidates CTE already excludes from re-claiming).- SELECT m.org_id, count(*) AS live- FROM {DUCKGRES_LEASE_TABLE} l- JOIN team_org m ON m.team_id = l.team_id- WHERE l.expires_at > now()- GROUP BY m.org_id- ),- candidates AS MATERIALIZED (- SELECT- {pending_batch_select_columns("dgs")}- FROM {BATCH_TABLE} b- JOIN run_starts rs_b ON rs_b.run_uuid = b.run_uuid- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {_team_scope("b", scoped=scoped)}- AND (%(eligible_schema_ids)s::varchar[] IS NULL OR b.schema_id = ANY(%(eligible_schema_ids)s))- -- In-flight groups: re-claiming them burns the LIMIT and- -- max_groups budget on work this pod can't start.- AND NOT (- %(exclude_team_ids)s::bigint[] IS NOT NULL- AND (b.team_id, b.schema_id) IN (- SELECT * FROM unnest(%(exclude_team_ids)s::bigint[], %(exclude_schema_ids)s::varchar[])- )- )- -- Other pods' live-leased groups are unclaimable; filter- -- BEFORE the LIMIT or one leased backfill can fill the- -- window and starve other schemas.- AND NOT EXISTS (- SELECT 1 FROM {DUCKGRES_LEASE_TABLE} bl- WHERE bl.team_id = b.team_id- AND bl.schema_id = b.schema_id- AND bl.expires_at > now()- AND bl.owner_token <> %(owner)s- )- -- Fully budget-saturated orgs are unclaimable too, and for- -- the same reason must be filtered BEFORE the LIMIT: a- -- saturated org's deep backlog (e.g. a pending backfill)- -- would otherwise fill the window with rows the group- -- filter then drops, and the pod claims nothing while- -- other orgs have work. Partially available orgs keep- -- their rows; candidate_groups ranks those per org below.- AND NOT EXISTS (- SELECT 1- FROM team_org m- JOIN org_usage u ON u.org_id = m.org_id- WHERE m.team_id = b.team_id- AND u.live >= m.budget- )- AND NOT {BLOCKED_LIVE_BATCH_CONDITION}- AND b.latest_state = 'succeeded'- AND (- dgs.batch_id IS NULL- OR (- dgs.job_state = 'waiting_retry'- AND dgs.created_at <= now() - make_interval(- secs => %(backoff)s * GREATEST(COALESCE(dgs.attempt, 1), 1)- )- )- )- AND (- -- Self-apply exclusion, scoped to statusless batches: an- -- applied batch with no duckgres status row must not be- -- re-claimed. A batch stranded in waiting_retry AFTER its- -- apply marker landed (crash between mark_applied and the- -- 'succeeded' write) stays claimable on purpose: its no-op- -- pass converges the status to 'succeeded'.- b.is_final_batch = true- OR dgs.batch_id IS NOT NULL- OR NOT EXISTS (- SELECT 1- FROM {DUCKGRES_APPLY_TABLE} current_apply- WHERE current_apply.team_id = b.team_id- AND current_apply.schema_id = b.schema_id- AND current_apply.run_uuid = b.run_uuid- AND current_apply.batch_index = b.batch_index- )- )- AND b.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)- AND NOT EXISTS (- SELECT 1- FROM {BATCH_TABLE} prev- LEFT JOIN {DUCKGRES_APPLY_TABLE} a- ON a.team_id = prev.team_id- AND a.schema_id = prev.schema_id- AND a.run_uuid = prev.run_uuid- AND a.batch_index = prev.batch_index- LEFT JOIN {_latest_status_lateral(STATUS_TABLE, "prev")} ds_prev ON true- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "prev")} dgs_prev ON true- WHERE prev.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND prev.team_id = b.team_id- AND prev.schema_id = b.schema_id- AND prev.run_uuid = b.run_uuid- AND prev.is_final_batch = false- AND (- prev.batch_index < b.batch_index- OR (b.is_final_batch = true AND prev.batch_index <= b.batch_index)- )- AND a.id IS NULL- AND (- -- Both batch kinds co-claim: a predecessor blocks- -- only when it cannot be returned AHEAD of this- -- batch in this same fetch (live batches gained- -- this in 2026-07; one-at-a-time head-of-line- -- capped a group at ~1 batch per fetch rotation- -- and could not keep up with a fast producer).- -- Not delta-succeeded (fail closed):- ds_prev.job_state IS DISTINCT FROM 'succeeded'- -- sorting later in the fetch order (a reconcile- -- replay re-inserts dropped chunks with a fresh- -- created_at):- OR (prev.created_at, prev.batch_index) > (b.created_at, b.batch_index)- OR dgs_prev.job_state = 'executing'- OR dgs_prev.job_state = 'succeeded'- OR (- dgs_prev.job_state = 'waiting_retry'- AND dgs_prev.created_at > now() - make_interval(- secs => %(backoff)s * GREATEST(COALESCE(dgs_prev.attempt, 1), 1)- )- )- )- )- AND (- -- Cross-run head-of-line: an older non-failed run of this- -- schema still has unapplied data batches. Applies to LIVE- -- batches only: a backfill run is ordered manually —- -- batches provably contained in its Delta snapshot are- -- pre-applied at plan time, and anything not contained must- -- apply AFTER the swap, so it must not gate the chunks. Live- -- batches still queue behind the backfill run itself via- -- this same check.- NOT EXISTS (- SELECT 1- FROM incomplete_runs ir- WHERE ir.team_id = b.team_id- AND ir.schema_id = b.schema_id- AND ir.run_uuid <> b.run_uuid- AND (ir.started_at, ir.run_uuid) < (rs_b.started_at, b.run_uuid)- -- A backfill chunk ignores older LIVE runs (see above)- -- but still orders behind an older backfill run, so- -- two generations can never interleave on the- -- staging table.- AND ({LIVE_BATCH_SQL_PREDICATE} OR ir.is_backfill_run)- )- )- ORDER BY b.created_at ASC, b.batch_index ASC, b.is_final_batch ASC- LIMIT %(limit)s- ),- candidate_groups AS (- -- Cap leased groups to the consumer's free slots, oldest work- -- first (NULL = no cap): a leased-but-unstarted group would be- -- renewed by every poll and stay dark to other pods. Groups of- -- an org with only PARTIAL budget left are ranked here and the- -- overflow skipped (fully saturated orgs never reached the- -- candidates window at all), so other orgs still fill max_groups.- SELECT g.team_id, g.schema_id- FROM (- SELECT- grp.team_id,- grp.schema_id,- grp.oldest,- CASE WHEN m.org_id IS NULL THEN NULL- ELSE row_number() OVER (- PARTITION BY m.org_id- ORDER BY grp.oldest ASC, grp.team_id ASC, grp.schema_id ASC- )- END AS org_rank,- m.budget - COALESCE(u.live, 0) AS org_remaining- FROM (- SELECT c.team_id, c.schema_id, min(c.created_at) AS oldest- FROM candidates c- GROUP BY c.team_id, c.schema_id- ) grp- LEFT JOIN team_org m ON m.team_id = grp.team_id- LEFT JOIN org_usage u ON u.org_id = m.org_id- ) g- WHERE g.org_rank IS NULL OR g.org_rank <= GREATEST(g.org_remaining, 0)- ORDER BY g.oldest ASC, g.team_id ASC, g.schema_id ASC- LIMIT COALESCE(%(max_groups)s, 2147483647)- ),- claimed AS (- INSERT INTO {DUCKGRES_LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at)- SELECT team_id, schema_id, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now()- FROM candidate_groups- ON CONFLICT (team_id, schema_id) DO UPDATE- SET owner_token = excluded.owner_token,- expires_at = excluded.expires_at,- acquired_at = CASE- WHEN {DUCKGRES_LEASE_TABLE}.owner_token = excluded.owner_token THEN {DUCKGRES_LEASE_TABLE}.acquired_at- ELSE now()- END,- updated_at = now()- WHERE {DUCKGRES_LEASE_TABLE}.expires_at < now()- OR {DUCKGRES_LEASE_TABLE}.owner_token = excluded.owner_token- RETURNING team_id, schema_id- )- SELECT c.*- FROM candidates c- JOIN claimed USING (team_id, schema_id)- ORDER BY c.created_at ASC, c.batch_index ASC, c.is_final_batch ASC- """,- {- "limit": limit,- "backoff": retry_backoff_base_seconds,- "team_ids": team_ids,- "blocked_schema_ids": blocked_schema_ids,- "eligible_schema_ids": eligible_schema_ids,- "owner": owner_token,- "ttl": lease_ttl_seconds,- "max_groups": max_groups,- "exclude_team_ids": [team_id for team_id, _ in exclude_groups] if exclude_groups else None,- "exclude_schema_ids": [schema_id for _, schema_id in exclude_groups] if exclude_groups else None,- "budget_team_ids": [team_id for team_id, _, _ in team_org_budgets] if team_org_budgets else [],- "budget_org_ids": [org_id for _, org_id, _ in team_org_budgets] if team_org_budgets else [],- "budget_values": [budget for _, _, budget in team_org_budgets] if team_org_budgets else [],- },- )- rows = await cur.fetchall()- return [PendingBatch(**row) for row in rows]-- @staticmethod- async def count_orgs_at_budget(- conn: psycopg.AsyncConnection[Any],- *,- team_org_budgets: list[tuple[int, str, int]],- ) -> int:- """How many orgs currently have live group leases at (or over) their sink- budget — the dashboard signal that backlog is budget-limited, not- pod-limited (raise the org's budget or duckgres capacity, not replicas)."""- if not team_org_budgets:- return 0- row = await conn.execute(- f"""- SELECT count(*)- FROM (- SELECT m.org_id- FROM {DUCKGRES_LEASE_TABLE} l- JOIN unnest(- %(budget_team_ids)s::bigint[],- %(budget_org_ids)s::varchar[],- %(budget_values)s::int[]- ) AS m(team_id, org_id, budget) ON m.team_id = l.team_id- WHERE l.expires_at > now()- GROUP BY m.org_id- HAVING count(*) >= max(m.budget)- ) saturated- """,- {- "budget_team_ids": [team_id for team_id, _, _ in team_org_budgets],- "budget_org_ids": [org_id for _, org_id, _ in team_org_budgets],- "budget_values": [budget for _, _, budget in team_org_budgets],- },- )- result = await row.fetchone()- return int(result[0]) if result else 0-- @staticmethod- async def supersede_replaced_runs(- conn: psycopg.AsyncConnection[Any],- *,- team_ids: list[int] | None = None,- ) -> int:- """Fail older runs' pending duckgres work once a newer replace-run is ready.-- When a newer run whose batch 0 will CREATE OR REPLACE the table (full- refresh, or first-ever incremental) is delta-succeeded and not yet- applied, any older run's remaining unapplied duckgres work is worthless —- applying it after the replace would mix stale rows into the new table.- Mark those batches 'failed' (reason: superseded) so the failed-run- exclusion retires them and the cross-run gate opens for the new run.-- Skips batches currently 'executing' (their attempt resolves on its own)- and anything already terminal. Returns the number of batches superseded.- """- scoped = team_ids is not None- async with _statement_timeout(conn, ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS), conn.cursor() as cur:- await cur.execute(- f"""- WITH {_eligibility_ctes(scoped)}- replace_heads AS MATERIALIZED (- SELECT nb.team_id, nb.schema_id, nb.run_uuid, rs.started_at- FROM {BATCH_TABLE} nb- JOIN run_starts rs ON rs.run_uuid = nb.run_uuid- LEFT JOIN {DUCKGRES_APPLY_TABLE} na- ON na.team_id = nb.team_id- AND na.schema_id = nb.schema_id- AND na.run_uuid = nb.run_uuid- AND na.batch_index = nb.batch_index- WHERE nb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {_team_scope("nb", scoped=scoped)}- AND nb.latest_state = 'succeeded'- AND nb.batch_index = 0- AND nb.is_final_batch = false- AND nb.is_resume = false- AND (- nb.sync_type = 'full_refresh'- OR (nb.sync_type = 'incremental' AND nb.is_first_ever_sync)- )- AND na.id IS NULL- AND nb.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)- ),- victims AS (- SELECT DISTINCT ON (old.id) old.id AS batch_id, rh.run_uuid AS superseded_by- FROM {BATCH_TABLE} old- JOIN replace_heads rh- ON rh.team_id = old.team_id AND rh.schema_id = old.schema_id- JOIN run_starts ors ON ors.run_uuid = old.run_uuid- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "old")} odgs ON true- LEFT JOIN {DUCKGRES_APPLY_TABLE} oa- ON oa.team_id = old.team_id- AND oa.schema_id = old.schema_id- AND oa.run_uuid = old.run_uuid- AND oa.batch_index = old.batch_index- WHERE old.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND old.run_uuid <> rh.run_uuid- AND (ors.started_at, old.run_uuid) < (rh.started_at, rh.run_uuid)- AND old.latest_state = 'succeeded'- AND old.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)- AND (old.is_final_batch = true OR oa.id IS NULL)- AND (odgs.batch_id IS NULL OR odgs.job_state = 'waiting_retry')- ORDER BY old.id, rh.started_at DESC, rh.run_uuid DESC- )- INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, error_response)- SELECT- v.batch_id,- 'failed',- 0,- jsonb_build_object('error', 'superseded by newer replace run ' || v.superseded_by, 'kind', '{RETIRE_KIND_SUPERSEDED_BY_REPLACE}')- FROM victims v- """,- {"team_ids": team_ids},- )- return cur.rowcount or 0-- @staticmethod- async def get_backlog_stats(- conn: psycopg.AsyncConnection[Any],- *,- team_ids: list[int] | None = None,- blocked_schema_ids: list[str] | None = None,- eligible_schema_ids: list[str] | None = None,- failing_schema_ids: list[str] | None = None,- ) -> 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- failure are time-bounded loss modes). Blocked = the same but held back- by an unprimed schema whose backfill is progressing normally; this is- the pageable bucket — it drains on its own, so sustained growth means a- real throughput problem. Failing-blocked = blocked batches behind a- hard-blocked schema (failure streak at threshold / needs_resync);- counted separately so one wedged schema can neither trigger nor mask- the page. Durable per-schema failure tracking lives on- sink state (this count ages out with queue retention).- """- scoped = team_ids is not None- async with _statement_timeout(conn, ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS), conn.cursor() as cur:- await cur.execute(- f"""- WITH {_eligibility_ctes(scoped)}- backlog AS (- SELECT- b.created_at,- {BLOCKED_LIVE_BATCH_CONDITION} AS is_blocked,- (- %(failing_schema_ids)s::varchar[] IS NOT NULL- AND b.schema_id = ANY(%(failing_schema_ids)s)- ) AS is_failing- FROM {BATCH_TABLE} b- LEFT JOIN {DUCKGRES_APPLY_TABLE} a- ON a.team_id = b.team_id- AND a.schema_id = b.schema_id- AND a.run_uuid = b.run_uuid- AND a.batch_index = b.batch_index- WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {_team_scope("b", scoped=scoped)}- AND (%(eligible_schema_ids)s::varchar[] IS NULL OR b.schema_id = ANY(%(eligible_schema_ids)s))- AND b.latest_state = 'succeeded'- AND b.is_final_batch = false- AND a.id IS NULL- AND b.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)- )- SELECT- count(*) FILTER (WHERE NOT is_blocked),- EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE NOT is_blocked)),- count(*) FILTER (WHERE is_blocked AND NOT is_failing),- EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE is_blocked AND NOT is_failing)),- count(*) FILTER (WHERE is_blocked AND is_failing)- FROM backlog- """,- {- "team_ids": team_ids,- "blocked_schema_ids": blocked_schema_ids,- "eligible_schema_ids": eligible_schema_ids,- "failing_schema_ids": failing_schema_ids,- },- )- row = await cur.fetchone()-- def _age(v: Any) -> float | None:- return float(v) if v is not None else None-- if row is None:- 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(- conn: psycopg.AsyncConnection[Any],- *,- batch_id: str,- job_state: str,- attempt: int = 0,- error_response: dict[str, Any] | None = None,- ) -> None:- await conn.execute(- f"""- INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- VALUES (%(batch_id)s, %(job_state)s, %(attempt)s, now(), %(error_response)s, now())- """,- {- "batch_id": batch_id,- "job_state": job_state,- "attempt": attempt,- "error_response": json.dumps(error_response) if error_response else None,- },- )-- @staticmethod- async def mark_applied(- conn: psycopg.AsyncConnection[Any],- *,- batch: PendingBatch,- ) -> None:- await conn.execute(- f"""- INSERT INTO {DUCKGRES_APPLY_TABLE} (- team_id, schema_id, run_uuid, batch_index, batch_id, row_count, created_at- ) VALUES (- %(team_id)s, %(schema_id)s, %(run_uuid)s, %(batch_index)s, %(batch_id)s, %(row_count)s, now()- )- ON CONFLICT (team_id, schema_id, run_uuid, batch_index) DO NOTHING- """,- {- "team_id": batch.team_id,- "schema_id": batch.schema_id,- "run_uuid": batch.run_uuid,- "batch_index": batch.batch_index,- "batch_id": batch.id,- "row_count": batch.row_count,- },- )-- @staticmethod- async def update_status_unless_failed(- conn: psycopg.AsyncConnection[Any],- *,- batch_id: str,- job_state: str,- attempt: int = 0,- error_response: dict[str, Any] | None = None,- ) -> bool:- """Append a status row only if the batch's latest status is not terminal 'failed'.-- The consumer routes every status write through this so a terminal- 'failed' (supersede/replan/fail_run can land at any point in a claimed- batch's lifecycle) is never masked by a later row in the latest-status- views. Guard and insert share one statement snapshot; returns False- (writing nothing) when the batch is retired.-- Accepted residual: a failure writer whose statement overlaps this one- can be mutually invisible. One statement wide, same class the supersede- design accepts by skipping 'executing' victims, converges via the- periodic sweeps — closing it needs a shared per-batch lock, not worth it.- """- cursor = await conn.execute(- f"""- INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- SELECT %(batch_id)s, %(job_state)s, %(attempt)s, now(), %(error_response)s, now()- WHERE (- SELECT cur.job_state- FROM {DUCKGRES_STATUS_TABLE} cur- WHERE cur.batch_id = %(batch_id)s- ORDER BY cur.created_at DESC, cur.id DESC- LIMIT 1- ) IS DISTINCT FROM 'failed'- """,- {- "batch_id": batch_id,- "job_state": job_state,- "attempt": attempt,- "error_response": json.dumps(error_response) if error_response else None,- },- )- return bool(cursor.rowcount)-- @staticmethod- async def requeue_stale_executing(- conn: psycopg.AsyncConnection[Any],- *,- batch: PendingBatch,- error_response: dict[str, Any],- grace_seconds: int,- ) -> bool:- """Flip a stale 'executing' batch to waiting_retry — fenced at write time.-- Between the unlocked stale scan and this write, the group can be- reclaimed, a rival sweep can requeue first, or a leaseless live worker- (old advisory-lock pod in the mixed-version window) can heartbeat a- fresh 'executing'. The insert re-checks all of it in its own snapshot:- latest status still 'executing', older than ``grace_seconds``, and no- live lease. Returns False when skipped; a later sweep retries.- """- cursor = await conn.execute(- f"""- INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- SELECT %(batch_id)s, 'waiting_retry', %(attempt)s, now(), %(error_response)s, now()- WHERE EXISTS (- SELECT 1- FROM (- SELECT cur.job_state, cur.created_at- FROM {DUCKGRES_STATUS_TABLE} cur- WHERE cur.batch_id = %(batch_id)s- ORDER BY cur.created_at DESC, cur.id DESC- LIMIT 1- ) latest- WHERE latest.job_state = 'executing'- AND latest.created_at <= now() - make_interval(secs => %(grace)s)- )- AND NOT EXISTS (- SELECT 1 FROM {DUCKGRES_LEASE_TABLE} l- WHERE l.team_id = %(team_id)s- AND l.schema_id = %(schema_id)s- AND l.expires_at > now()- )- """,- {- "batch_id": batch.id,- "attempt": batch.latest_attempt,- "error_response": json.dumps(error_response),- "team_id": batch.team_id,- "schema_id": batch.schema_id,- "grace": grace_seconds,- },- )- return bool(cursor.rowcount)-- @staticmethod- async def fail_run_if_stale(- conn: psycopg.AsyncConnection[Any],- *,- batch: PendingBatch,- reason: str,- grace_seconds: int,- ) -> bool:- """Terminally fail a run from recovery — fenced inside the insert itself.-- Same fence as ``requeue_stale_executing``, keyed on the anchor batch:- the failure rows land only while its latest status is still 'executing',- older than ``grace_seconds``, and the group has no live lease — all in- this statement's snapshot. Returns False when the fence refuses. The- group error path uses ``fail_run`` instead, since it legitimately fails- runs while holding its own live lease.- """- cursor = await conn.execute(- f"""- INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)- SELECT b.id, 'failed', 0, now(), %(error_response)s, now()- FROM {BATCH_TABLE} b- JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON true- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true- WHERE- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND b.run_uuid = %(run_uuid)s- AND ds.job_state = 'succeeded'- AND (dgs.batch_id IS NULL OR dgs.job_state IN ('waiting_retry', 'executing'))- AND EXISTS (- SELECT 1- FROM (- SELECT anchor.job_state, anchor.created_at- FROM {DUCKGRES_STATUS_TABLE} anchor- WHERE anchor.batch_id = %(anchor_batch_id)s- ORDER BY anchor.created_at DESC, anchor.id DESC- LIMIT 1- ) latest- WHERE latest.job_state = 'executing'- AND latest.created_at <= now() - make_interval(secs => %(grace)s)- )- AND NOT EXISTS (- SELECT 1 FROM {DUCKGRES_LEASE_TABLE} l- WHERE l.team_id = %(team_id)s- AND l.schema_id = %(schema_id)s- AND l.expires_at > now()- )- """,- {- "run_uuid": batch.run_uuid,- "anchor_batch_id": batch.id,- "team_id": batch.team_id,- "schema_id": batch.schema_id,- "error_response": json.dumps({"error": reason}),- "grace": grace_seconds,- },- )- return bool(cursor.rowcount)-- @staticmethod- async def is_failed(- conn: psycopg.AsyncConnection[Any],- *,- batch_id: str,- ) -> bool:- """Whether the batch's LATEST duckgres status is terminal 'failed' — the- consumer's per-batch re-check for co-claimed batches retired mid-claim."""- async with conn.cursor() as cur:- await cur.execute(- f"""- SELECT job_state- FROM {DUCKGRES_STATUS_TABLE}- WHERE batch_id = %(batch_id)s- ORDER BY created_at DESC, id DESC- LIMIT 1- """,- {"batch_id": batch_id},- )- row = await cur.fetchone()- return bool(row and row[0] == "failed")-- @staticmethod- async def has_applied(- conn: psycopg.AsyncConnection[Any],- *,- batch: PendingBatch,- ) -> bool:- row = await conn.execute(- f"""- SELECT 1- FROM {DUCKGRES_APPLY_TABLE}- WHERE team_id = %(team_id)s- AND schema_id = %(schema_id)s- AND run_uuid = %(run_uuid)s- AND batch_index = %(batch_index)s- LIMIT 1- """,- {- "team_id": batch.team_id,- "schema_id": batch.schema_id,- "run_uuid": batch.run_uuid,- "batch_index": batch.batch_index,- },- )- return await row.fetchone() is not None-- @staticmethod- async def fail_run(- conn: psycopg.AsyncConnection[Any],- *,- run_uuid: str,- reason: str,- ) -> int:- cursor = await conn.execute(- DUCKGRES_FAIL_RUN_SQL,- {- "run_uuid": run_uuid,- "error_response": json.dumps({"error": reason}),- },- )- return cursor.rowcount or 0-- @staticmethod- def fail_run_sync(- conn: psycopg.Connection[Any],- *,- run_uuid: str,- reason: str,- ) -> int:- """Sync twin of ``fail_run`` for the ops management command."""- cursor = conn.execute(- DUCKGRES_FAIL_RUN_SQL,- {- "run_uuid": run_uuid,- "error_response": json.dumps({"error": reason}),- },- )- return cursor.rowcount or 0-- @staticmethod- async def verify_lease(- conn: psycopg.AsyncConnection[Any],- *,- team_id: int,- schema_id: str,- owner_token: str,- ) -> bool:- """Check whether ``owner_token`` still holds a live group lease for (team_id, schema_id)."""- async with conn.cursor() as cur:- await cur.execute(- f"""- SELECT EXISTS (- SELECT 1 FROM {DUCKGRES_LEASE_TABLE}- WHERE team_id = %(team_id)s- AND schema_id = %(schema_id)s- AND owner_token = %(owner)s- AND expires_at > now()- )- """,- {"team_id": team_id, "schema_id": schema_id, "owner": owner_token},- )- row = await cur.fetchone()- return bool(row and row[0])-- @staticmethod- async def renew_lease(- conn: psycopg.AsyncConnection[Any],- *,- team_id: int,- schema_id: str,- owner_token: str,- lease_ttl_seconds: int = LEASE_TTL_SECONDS,- ) -> bool:- """Extend this owner's group lease. Returns False when lost (gone,- reclaimed, or expired) — an expired lease must never be resurrected here- (recovery may have re-queued the group); re-claiming goes through the- fetch's claim CTE only.- """- async with conn.cursor() as cur:- await cur.execute(- f"""- UPDATE {DUCKGRES_LEASE_TABLE}- SET expires_at = now() + make_interval(secs => %(ttl)s), updated_at = now()- WHERE team_id = %(team_id)s- AND schema_id = %(schema_id)s- AND owner_token = %(owner)s- AND expires_at > now()- RETURNING 1- """,- {"team_id": team_id, "schema_id": schema_id, "owner": owner_token, "ttl": lease_ttl_seconds},- )- return (await cur.fetchone()) is not None-- @staticmethod- async def get_stale_executing(- conn: psycopg.AsyncConnection[Any],- *,- grace_seconds: int = 0,- ) -> list[PendingBatch]:- """Find batches stuck in 'executing' whose group lease is absent or- expired — unlike the old advisory-lock probe, an abandoned lease always- expires, so orphaned groups are always reclaimable."""- async with conn.cursor(row_factory=dict_row) as cur:- await cur.execute(_stale_executing_sql(), {"grace": grace_seconds})- rows = await cur.fetchall()-- return [PendingBatch(**row) for row in rows]-- @staticmethod- async def unlock_for_batches(- conn: psycopg.AsyncConnection[Any],- *,- batches: list[PendingBatch],- owner_token: str,- ) -> None:- """Release the group leases for ``batches``' groups held by ``owner_token``- — the owner predicate keeps this a no-op if another pod reclaimed the group."""- pairs = list({(b.team_id, b.schema_id) for b in batches})- if not pairs:- return- team_ids = [team_id for team_id, _ in pairs]- schema_ids = [schema_id for _, schema_id in pairs]- await conn.execute(- f"""- DELETE FROM {DUCKGRES_LEASE_TABLE}- WHERE owner_token = %(owner)s- AND (team_id, schema_id) IN (- SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])- )- """,- {"owner": owner_token, "team_ids": team_ids, "schema_ids": schema_ids},- )-- @staticmethod- async def release_all_owned_leases(- conn: psycopg.AsyncConnection[Any],- *,- owner_token: str,- ) -> None:- """Delete every group lease held by ``owner_token``. Best-effort cleanup on shutdown."""- await conn.execute(- f"DELETE FROM {DUCKGRES_LEASE_TABLE} WHERE owner_token = %(owner)s",- {"owner": owner_token},- )-- # -- ops / management command helpers (sync) --------------------------------- # Duck-typed twins of BatchQueue's ops helpers so manage_warehouse_queue can- # drive either sink through the same interface.-- @staticmethod- def get_active_runs(- conn: psycopg.Connection[Any],- *,- team_id: int | None = None,- schema_ids: list[str] | None = None,- run_uuid: str | None = None,- only_pending: bool = True,- ) -> list[ActiveRunRef]:- """Aggregate queue batches per run by their duckgres sink state.-- ``pending_batches`` counts batches the duckgres sink still owes: delta-- succeeded but with no terminal duckgres status (the same predicate- ``fail_run`` writes against). ``latest_activity_at`` is the newest of- batch inserts, delta status writes, and duckgres status writes, so a run- the delta consumer is still actively loading does not look duckgres-stuck.- """- scope_sql, params = scope_filters(team_id=team_id, schema_ids=schema_ids, run_uuid=run_uuid)- having = f"HAVING COUNT(*) FILTER (WHERE {duckgres_pending_predicate('ds', 'dgs')}) > 0"- with conn.cursor(row_factory=dict_row) as cur:- cur.execute(- f"""- SELECT- b.run_uuid,- b.team_id,- b.schema_id,- MAX(b.job_id) AS job_id,- MAX(b.source_id) AS source_id,- MAX(b.metadata->>'workflow_run_id') AS workflow_run_id,- COUNT(*) FILTER (- WHERE {duckgres_pending_predicate("ds", "dgs")}- ) AS pending_batches,- COUNT(*) AS total_batches,- GREATEST(MAX(ds.created_at), MAX(dgs.created_at), MAX(b.created_at)) AS latest_activity_at- FROM {BATCH_TABLE} b- LEFT JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON true- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true- WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {scope_sql}- GROUP BY b.run_uuid, b.team_id, b.schema_id- {having if only_pending else ""}- ORDER BY latest_activity_at ASC- """,- params,- )- rows = cur.fetchall()- return [ActiveRunRef(**row) for row in rows]-- @staticmethod- def get_state_summary(- conn: psycopg.Connection[Any],- *,- team_id: int | None = None,- schema_ids: list[str] | None = None,- ) -> list[dict[str, Any]]:- """Delta-succeeded batch counts by latest duckgres state within the scope.-- Scoped to delta-succeeded batches because that is the duckgres sink's- input set; ``state='unclaimed'`` means the sink has not touched the- batch yet. Each row carries the oldest ``created_at`` in its state.- """- scope_sql, params = scope_filters(team_id=team_id, schema_ids=schema_ids)- with conn.cursor(row_factory=dict_row) as cur:- cur.execute(- f"""- SELECT- COALESCE(dgs.job_state, 'unclaimed') AS state,- COUNT(*) AS batch_count,- MIN(b.created_at) AS oldest_created_at- FROM {BATCH_TABLE} b- JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON ds.job_state = 'succeeded'- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true- WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- {scope_sql}- GROUP BY 1- ORDER BY 1- """,- params,- )- return cur.fetchall()-- @staticmethod- def get_leases(- conn: psycopg.Connection[Any],- *,- team_id: int | None = None,- schema_ids: list[str] | None = None,- ) -> list[GroupLease]:- """Duckgres group leases within the scope, with computed liveness."""- scope_sql, params = scope_filters(team_id=team_id, schema_ids=schema_ids, alias="l")- with conn.cursor(row_factory=dict_row) as cur:- cur.execute(- f"""- SELECT team_id, schema_id, owner_token, acquired_at, updated_at, expires_at,- expires_at > now() AS is_live- FROM {DUCKGRES_LEASE_TABLE} l- WHERE true- {scope_sql}- ORDER BY team_id, schema_id- """,- params,- )- rows = cur.fetchall()- return [GroupLease(**row) for row in rows]-- @staticmethod- def force_release_leases(- conn: psycopg.Connection[Any],- *,- pairs: list[tuple[int, str]],- ) -> int:- """Delete duckgres group leases for ``pairs`` regardless of owner. Ops override only."""- if not pairs:- return 0- cursor = conn.execute(- f"""- DELETE FROM {DUCKGRES_LEASE_TABLE}- WHERE (team_id, schema_id) IN (- SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])- )- """,- {- "team_ids": [team_id for team_id, _ in pairs],- "schema_ids": [schema_id for _, schema_id in pairs],- },- )- return cursor.rowcount or 0-- @staticmethod- def get_stale_executing_sync(- conn: psycopg.Connection[Any],- *,- grace_seconds: int = 0,- team_id: int | None = None,- schema_ids: list[str] | None = None,- ) -> list[PendingBatch]:- """Sync, scope-filtered twin of ``get_stale_executing`` for ops inspection."""- scope_sql, params = scope_filters(team_id=team_id, schema_ids=schema_ids)- params["grace"] = grace_seconds- with conn.cursor(row_factory=dict_row) as cur:- cur.execute(_stale_executing_sql(scope_sql), params)- rows = cur.fetchall()- return [PendingBatch(**row) for row in rows]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/load.pydeleted file mode 100644index 39fc1e448e57..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/load.py+++ /dev/null@@ -1,19 +0,0 @@-from __future__ import annotations--from asgiref.sync import sync_to_async--from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor import (- process_batch as process_sync,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- PendingBatch,-)---async def process_batch(batch: PendingBatch) -> None:- # thread_sensitive=False: the default would funnel every batch through- # asgiref's process-global single-thread executor, reducing the consumer's- # real parallelism to 1 regardless of max_concurrency. Each batch is- # self-contained (own Django reads after close_old_connections, own duckgres- # connection), so cross-thread execution is safe.- await sync_to_async(process_sync, thread_sensitive=False)(batch)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.pydeleted file mode 100644index 6261b0c71c39..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py+++ /dev/null@@ -1,940 +0,0 @@-from __future__ import annotations--import time-import atexit-import threading-from collections.abc import Iterator-from contextlib import contextmanager-from dataclasses import dataclass-from time import sleep as _real_sleep # captured before any test patches this module's `time`-from typing import Any, Literal-from weakref import WeakKeyDictionary--from django.conf import settings-from django.db import close_old_connections--import psycopg-import structlog-from prometheus_client import Histogram-from psycopg import sql--from posthog.models import Team--from products.managed_warehouse.backend.facade.api import (- duckgres_data_imports_schema,- duckgres_data_imports_table_name,- get_duckgres_query_server_config,- setup_duckgres_session,-)-from products.warehouse_sources.backend.models import ExternalDataJob, ExternalDataSchema-from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (- PermanentBatchApplyError,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import batch_kind-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- PendingBatch,-)--logger = structlog.get_logger(__name__)--DUCKGRES_APPLY_TABLE = "_posthog_source_batch_duckgres_apply"--# Duckgres-side apply markers older than this are pruned opportunistically at the-# start of each run. Must comfortably exceed the queue's eligibility window-# (PARTITION_PRUNING_INTERVAL, 14d) — the ordering gate and has_applied read them.-APPLY_MARKER_RETENTION_DAYS = 30--EXTRACT_READ_SECRET_NAME = "posthog_extract_read"--# Per-batch apply latency, split by phase and kind. Fine buckets on purpose: the-# shared engine histogram (batch_processing_duration_seconds) floors at 0.5s, so-# this is the only place sub-second live-apply latency and the backfill phase-# breakdown (schema_read vs data_load vs swap) are observable.-_PHASE_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0)--APPLY_PHASE_DURATION_SECONDS = Histogram(- "duckgres_sink_apply_phase_duration_seconds",- "Duckgres sink per-batch apply latency by phase (connect_setup, schema_read, data_load/apply, swap) and kind (live/backfill)",- labelnames=["phase", "kind"],- buckets=_PHASE_BUCKETS,-)--BACKFILL_CHUNK_FILES = Histogram(- "duckgres_sink_backfill_chunk_files",- "Source parquet files per backfill chunk — drives read_parquet/union_by_name footer-read cost",- buckets=(1, 2, 5, 10, 25, 50, 100, 200, 350, 512),-)---def _record_phase(phase: str, kind: str, elapsed: float, acc: dict[str, float]) -> None:- """Observe a phase's wall time on the histogram and record it (ms) into ``acc`` for logging."""- APPLY_PHASE_DURATION_SECONDS.labels(phase=phase, kind=kind).observe(elapsed)- acc[phase] = round(elapsed * 1000, 1)---@contextmanager-def _timed(phase: str, kind: str, acc: dict[str, float]) -> Iterator[None]:- """Time a block and record the phase even if it raises (mirrors error-path capture)."""- start = time.monotonic()- try:- yield- finally:- _record_phase(phase, kind, time.monotonic() - start, acc)---class DuckgresBatchAlreadyAppliedError(Exception):- """A concurrent processor applied this batch first; our write was rolled back."""---@dataclass(frozen=True)-class DuckgresColumn:- name: str- type_sql: str---@dataclass(frozen=True)-class BatchApplyOperation:- kind: Literal["replace", "create", "insert", "merge"]- ensure_target_columns: bool = False- primary_keys: list[str] | None = None---class _DuckgresSessionCache:- """Reuse one duckgres connection across consecutive live batches of a group.-- The dominant per-batch costs measured in prod (2026-07-22) are per-SESSION- fixed costs, not row volume: worker session create (~0.5-1s), the extended-- protocol describe probe's cold catalog enumeration (~5-19s), and the- transaction's first-write metadata touch on the target table (~12-19s).- All are warm on a reused session, taking a live batch from ~30-40s to ~2s.-- Keyed by (org_id, team_id, schema_id): the sink's group lease serializes- each (team, schema) to one pod task at a time, so entries are never used- concurrently — the lock guards only the dict. The org is part of the key- so a team transferred between organizations can never keep writing through- the previous org's authenticated connection. Entries are dropped on any- processing error (the connection may hold aborted-transaction state), after- IDLE_TTL without reuse, and past MAX_AGE outright (the extract-read secret- embeds session credentials that expire; a fresh session re-mints them).- A daemon sweeper enforces both bounds independently of traffic — without- it, a drained group's session would pin its duckgres worker (one session- per worker) indefinitely, outside the sink's org connection budget; with- it, the pin is bounded by IDLE_TTL + SWEEP_INTERVAL. atexit clears the- cache on graceful shutdown.- """-- IDLE_TTL_SECONDS = 90.0- MAX_AGE_SECONDS = 600.0- SWEEP_INTERVAL_SECONDS = 30.0- # Retained sessions pin duckgres workers, so cap them per org: even a burst- # of sequentially drained groups can never hold more than this many of an- # org's connections beyond its active leases (per consumer pod).- MAX_SESSIONS_PER_ORG = 4-- def __init__(self) -> None:- self._lock = threading.Lock()- self._entries: dict[tuple[str, int, str], tuple[psycopg.Connection[Any], float, float]] = {}- self._sweeper_started = False-- def acquire(self, org_id: str, team_id: int, schema_id: str) -> tuple[psycopg.Connection[Any] | None, float]:- """Return (connection, session_created_at); (None, now) means connect fresh.-- created_at is threaded back through store() so the MAX_AGE credential- cap tracks the ORIGINAL session creation across any number of reuses.- """- key = (org_id, team_id, schema_id)- now = time.monotonic()- with self._lock:- entry = self._entries.pop(key, None)- if entry is None:- return None, now- conn, created_at, last_used = entry- if now - last_used > self.IDLE_TTL_SECONDS or now - created_at > self.MAX_AGE_SECONDS:- self._close_quietly(conn)- return None, now- return conn, created_at-- def store(- self, org_id: str, team_id: int, schema_id: str, conn: psycopg.Connection[Any], created_at: float- ) -> None:- self._ensure_sweeper()- key = (org_id, team_id, schema_id)- overflow = []- with self._lock:- previous = self._entries.get(key)- self._entries[key] = (conn, created_at, time.monotonic())- org_keys = [k for k in self._entries if k[0] == org_id]- if len(org_keys) > self.MAX_SESSIONS_PER_ORG:- org_keys.sort(key=lambda k: self._entries[k][2]) # oldest last-use first- for stale_key in org_keys[: len(org_keys) - self.MAX_SESSIONS_PER_ORG]:- overflow.append(self._entries.pop(stale_key))- if previous is not None and previous[0] is not conn:- self._close_quietly(previous[0])- for other_conn, _, _ in overflow:- self._close_quietly(other_conn)-- def _ensure_sweeper(self) -> None:- # Lazy start: this module is imported by processes that never run the- # sink; only a process that actually caches a session gets the thread.- with self._lock:- if self._sweeper_started:- return- self._sweeper_started = True- threading.Thread(target=self._sweep_loop, daemon=True, name="duckgres-session-cache-sweeper").start()-- def _sweep_loop(self) -> None:- while True:- _real_sleep(self.SWEEP_INTERVAL_SECONDS)- try:- self._evict_stale()- except Exception:- pass-- def _evict_stale(self) -> None:- """Close entries past either bound — runs on the sweeper, not on traffic."""- now = time.monotonic()- with self._lock:- stale = [- k- for k, (_, created_at, used) in self._entries.items()- if now - used > self.IDLE_TTL_SECONDS or now - created_at > self.MAX_AGE_SECONDS- ]- evicted = [self._entries.pop(k) for k in stale]- for conn, _, _ in evicted:- self._close_quietly(conn)-- def clear(self) -> None:- with self._lock:- entries = list(self._entries.values())- self._entries.clear()- for conn, _, _ in entries:- self._close_quietly(conn)-- @staticmethod- def _close_quietly(conn: psycopg.Connection[Any]) -> None:- try:- conn.close()- except Exception:- pass---_session_cache = _DuckgresSessionCache()-atexit.register(_session_cache.clear)---def process_batch(batch: PendingBatch) -> None:- # Threads are reused across batches; drop stale app-DB connections so the ORM- # reads below reconnect instead of failing every attempt after a DB bounce.- close_old_connections()-- schema: ExternalDataSchema- if _is_backfill_batch(batch):- # Synthetic backfill batches carry a sentinel job_id; resolve the schema- # directly instead of via ExternalDataJob.- schema = ExternalDataSchema.objects.select_related("source").get(- id=batch.schema_id,- team_id=batch.team_id,- )- else:- job = ExternalDataJob.objects.select_related("schema", "schema__source").get(- id=batch.job_id,- team_id=batch.team_id,- )- if job.schema is None:- raise ValueError(f"ExternalDataJob {batch.job_id} has no schema")- schema = job.schema-- kind = "backfill" if _is_backfill_batch(batch) else "live"- # One ORM lookup serves both the cache key and the connection config; it is- # per-batch on purpose so the key always reflects the team's CURRENT org.- org_id = str(Team.objects.only("organization_id").get(id=batch.team_id).organization_id)- timings: dict[str, float] = {}- # Connect + session + secret is a fixed cost; measured as one phase so the- # connection-reuse win is visible against the apply itself (a cache hit- # records ~0). Recorded in a finally so a slow/failing connect (e.g.- # cold-tenant activation timeout) still lands in the phase metric.- connect_start = time.monotonic()- if kind == "backfill":- # Backfills are rare, long, and chunk-coalesced already — keep the- # simple fresh-connection lifecycle.- try:- with _connect_to_duckgres(org_id) as conn:- # The sink only reads parquet over S3; httpfs is bundled in the duckgres- # worker image so INSTALL is a local no-op. Do NOT add extensions that are- # not bundled (e.g. delta): egress-restricted workers silently drop the- # CDN download and the statement hangs.- setup_duckgres_session(conn, extensions=("httpfs",))- _create_extract_read_secret(conn)- _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)- try:- _process_backfill_batch(conn, batch, schema, timings=timings)- except DuckgresBatchAlreadyAppliedError:- _log_applied_by_concurrent_processor(batch)- finally:- if "connect_setup" not in timings:- _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)- return-- # Distinct name from the backfill branch's `with ... as conn` binding: this- # one is Optional until the cache miss connects, and mypy types by first use.- session_conn, session_created_at = _session_cache.acquire(org_id, batch.team_id, batch.schema_id)- try:- if session_conn is None:- session_conn = _connect_to_duckgres(org_id)- setup_duckgres_session(session_conn, extensions=("httpfs",))- _create_extract_read_secret(session_conn)- _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)- try:- _process_batch(session_conn, batch, schema, timings=timings)- except DuckgresBatchAlreadyAppliedError:- _log_applied_by_concurrent_processor(batch)- except BaseException:- # The connection may hold aborted-transaction or half-streamed state;- # never cache it. The queue's retry gets a fresh session.- if session_conn is not None:- _DuckgresSessionCache._close_quietly(session_conn)- raise- else:- _session_cache.store(org_id, batch.team_id, batch.schema_id, session_conn, created_at=session_created_at)- finally:- if "connect_setup" not in timings:- _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)---def _log_applied_by_concurrent_processor(batch: PendingBatch) -> None:- # A concurrent processor (lost advisory-lock session + recovery sweep)- # won the marker insert; its committed write is the canonical one and- # ours rolled back. Treat as applied.- logger.info(- "duckgres_batch_applied_by_concurrent_processor",- team_id=batch.team_id,- schema_id=batch.schema_id,- run_uuid=batch.run_uuid,- batch_index=batch.batch_index,- )---def _connect_to_duckgres(org_id: str) -> psycopg.Connection[Any]:- config = get_duckgres_query_server_config(org_id)- return psycopg.connect(- host=config.host,- port=config.port,- dbname=config.database,- user=config.username,- password=config.password,- autocommit=True,- # A half-open connection to a dead worker would otherwise block the sync- # thread for the OS TCP timeout (hours). Keepalives bound it to ~2 minutes;- # the consumer's stuck-batch watchdog is the backstop above that.- connect_timeout=30,- keepalives=1,- keepalives_idle=60,- keepalives_interval=15,- keepalives_count=4,- )---def _create_extract_read_secret(conn: psycopg.Connection[Any]) -> None:- """Grant this duckgres session read access to PostHog's extract bucket.-- read_parquet() executes on the duckgres worker, whose ambient credentials are- org-scoped to the org's own lake bucket — they cannot read the internal- DATAWAREHOUSE_BUCKET where v3 batches live. Mint short-lived credentials from- the consumer's own identity and inject them as a session secret SCOPEd to the- extract bucket, so it wins prefix resolution there and nowhere else.- """- bucket = settings.DATAWAREHOUSE_BUCKET- scope = f"s3://{bucket}"-- if settings.USE_LOCAL_SETUP:- parts = [- "TYPE S3",- f"KEY_ID {_sql_str(settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY)}",- f"SECRET {_sql_str(settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET)}",- f"ENDPOINT {_sql_str(settings.OBJECT_STORAGE_ENDPOINT.replace('http://', '').replace('https://', ''))}",- "URL_STYLE 'path'",- "USE_SSL false",- f"SCOPE {_sql_str(scope)}",- ]- else:- import boto3-- session = boto3.Session()- creds = session.get_credentials()- if creds is None:- raise RuntimeError("No AWS credentials available to read the extract bucket from duckgres")- frozen = creds.get_frozen_credentials()- if not frozen.access_key or not frozen.secret_key:- raise RuntimeError("AWS credential chain resolved without an access key pair")- parts = [- "TYPE S3",- f"KEY_ID {_sql_str(frozen.access_key)}",- f"SECRET {_sql_str(frozen.secret_key)}",- f"REGION {_sql_str(session.region_name or 'us-east-1')}",- f"SCOPE {_sql_str(scope)}",- ]- if frozen.token:- parts.insert(3, f"SESSION_TOKEN {_sql_str(frozen.token)}")-- conn.execute(- f"CREATE OR REPLACE SECRET {EXTRACT_READ_SECRET_NAME} ({', '.join(parts)})" # noqa: S608- )---def _sql_str(value: str) -> str:- return "'" + str(value).replace("'", "''") + "'"---def _is_backfill_batch(batch: PendingBatch) -> bool:- return batch_kind.is_backfill_metadata(batch.metadata)---def _backfill_chunk_paths(batch: PendingBatch) -> list[str]:- try:- return batch_kind.backfill_chunk_paths(batch.metadata)- except ValueError as e:- # Falling back to s3_path would silently apply only the chunk's first- # file; a malformed synthetic row must fail loudly instead.- raise PermanentBatchApplyError(f"backfill batch {batch.id}: {e}") from e---def _read_parquet_expr(paths: list[str], *, union_by_name: bool = False) -> sql.Composable:- """read_parquet([...]) with inlined literals — list parameters do not bind- reliably over the duckgres extended protocol. union_by_name aligns- schema-evolved files within one chunk by column name (backfill chunks span- months of Delta writes; positional unification fails on added columns)."""- opts = sql.SQL(", union_by_name=true") if union_by_name else sql.SQL("")- return sql.SQL("read_parquet([{}]{})").format(- sql.SQL(", ").join(sql.Literal(p) for p in paths),- opts,- )---def _backfill_table_name(live_table: str, schema_id: str) -> str:- # Suffix with a schema-id fragment: pure prefix truncation could collide- # for two schemas sharing a long name prefix in the same team schema.- return f"{live_table[:42]}__bf_{schema_id.replace('-', '')[:8]}"---def _process_batch(- conn: psycopg.Connection[Any],- batch: PendingBatch,- schema: ExternalDataSchema,- timings: dict[str, float] | None = None,-) -> None:- timings = timings if timings is not None else {}- duckgres_schema = _duckgres_schema_name(batch.team_id)- duckgres_table = _duckgres_table_name(schema)-- conn.execute(- sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(duckgres_schema)),- )-- if batch.sync_type == "cdc":- raise PermanentBatchApplyError("Duckgres batch sink does not support CDC batches yet")-- _ensure_duckgres_apply_table(conn, duckgres_schema)- if batch.batch_index == 0 and not batch.is_final_batch:- _prune_duckgres_apply_markers(conn, duckgres_schema)- if _has_duckgres_batch_applied(conn, duckgres_schema, batch=batch):- logger.info(- "duckgres_batch_already_applied",- team_id=batch.team_id,- schema_id=batch.schema_id,- run_uuid=batch.run_uuid,- batch_index=batch.batch_index,- )- return-- with _timed("schema_read", "live", timings):- parquet_schema = _read_parquet_schema(conn, [batch.s3_path])- columns = [column.name for column in parquet_schema]- operation = _plan_batch_operation(- conn,- batch,- duckgres_schema=duckgres_schema,- duckgres_table=duckgres_table,- )-- if operation.kind == "replace":- logger.info(- "duckgres_replacing_table_from_batch",- team_id=batch.team_id,- schema_id=batch.schema_id,- batch_index=batch.batch_index,- table=duckgres_table,- )-- with _timed("apply", "live", timings), conn.transaction():- if operation.ensure_target_columns:- _ensure_target_columns(conn, duckgres_schema, duckgres_table, parquet_schema)- _apply_batch_operation(- conn,- operation,- duckgres_schema=duckgres_schema,- duckgres_table=duckgres_table,- paths=[batch.s3_path],- columns=columns,- )- _mark_duckgres_batch_applied(conn, duckgres_schema, batch=batch)- return---def _process_backfill_batch(- conn: psycopg.Connection[Any],- batch: PendingBatch,- schema: ExternalDataSchema,- timings: dict[str, float] | None = None,-) -> None:- """Apply one backfill chunk into <table>__backfill; the last chunk swaps it live.-- See BACKFILL_SPEC.md. The swap (DROP live + RENAME) shares the last chunk's- transaction together with the apply-marker arbiter, so it is atomic and- exactly-once even with a concurrent processor.- """- timings = timings if timings is not None else {}- duckgres_schema = _duckgres_schema_name(batch.team_id)- live_table = _duckgres_table_name(schema)- backfill_table = _backfill_table_name(live_table, batch.schema_id)- chunk_count = batch_kind.backfill_chunk_count(batch.metadata)- is_last = chunk_count > 0 and batch.batch_index == chunk_count - 1-- conn.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(duckgres_schema)))- _ensure_duckgres_apply_table(conn, duckgres_schema)-- if _has_duckgres_batch_applied(conn, duckgres_schema, batch=batch):- logger.info(- "duckgres_backfill_chunk_already_applied",- team_id=batch.team_id,- schema_id=batch.schema_id,- run_uuid=batch.run_uuid,- batch_index=batch.batch_index,- )- if is_last:- # Crash between the swap's commit and the state flip lands here on- # retry: the swap is proven (the marker shared its transaction),- # only the app-DB flip is missing. Idempotent via CAS.- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (- mark_primed,- )-- mark_primed(batch.schema_id, run_uuid=batch.run_uuid, chunks_applied=chunk_count)- return-- chunk_paths = _backfill_chunk_paths(batch)- BACKFILL_CHUNK_FILES.observe(len(chunk_paths))- with _timed("schema_read", "backfill", timings):- parquet_schema = _read_parquet_schema(conn, chunk_paths, union_by_name=True)- columns = [column.name for column in parquet_schema]-- with conn.transaction():- with _timed("data_load", "backfill", timings):- if batch.batch_index == 0:- # CREATE OR REPLACE makes a re-planned backfill self-cleaning.- conn.execute(- sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(backfill_table),- _read_parquet_expr(chunk_paths, union_by_name=True),- )- )- else:- _ensure_target_columns(conn, duckgres_schema, backfill_table, parquet_schema)- _insert_batch(conn, duckgres_schema, backfill_table, chunk_paths, columns, union_by_name=True)-- if is_last:- logger.info(- "duckgres_backfill_swapping",- team_id=batch.team_id,- schema_id=batch.schema_id,- run_uuid=batch.run_uuid,- table=live_table,- chunk_count=chunk_count,- )- with _timed("swap", "backfill", timings):- conn.execute(- sql.SQL("DROP TABLE IF EXISTS {}.{}").format(- sql.Identifier(duckgres_schema), sql.Identifier(live_table)- )- )- conn.execute(- sql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(backfill_table),- sql.Identifier(live_table),- )- )-- _mark_duckgres_batch_applied(conn, duckgres_schema, batch=batch)-- logger.info(- "duckgres_backfill_chunk_timing",- team_id=batch.team_id,- schema_id=batch.schema_id,- run_uuid=batch.run_uuid,- batch_index=batch.batch_index,- chunk_count=chunk_count,- is_last=is_last,- file_count=len(chunk_paths),- connect_setup_ms=timings.get("connect_setup"),- schema_read_ms=timings.get("schema_read"),- data_load_ms=timings.get("data_load"),- swap_ms=timings.get("swap"),- )-- if is_last:- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (- mark_primed,- )-- mark_primed(batch.schema_id, run_uuid=batch.run_uuid, chunks_applied=chunk_count)- logger.info(- "duckgres_backfill_swapped",- team_id=batch.team_id,- schema_id=batch.schema_id,- table=live_table,- )---def _duckgres_schema_name(team_id: int) -> str:- # Resolves to posthog_data_imports_<schema> from the team's duckgres control-plane- # row (the same identifier that names its events/persons tables), else the legacy- # posthog_data_imports_team_<id>.- return duckgres_data_imports_schema(team_id)---def _duckgres_table_name(schema: ExternalDataSchema) -> str:- return duckgres_data_imports_table_name(schema)---def _should_replace_table(batch: PendingBatch) -> bool:- if batch.batch_index != 0 or batch.is_resume:- return False- if batch.sync_type == "full_refresh":- return True- if batch.sync_type == "incremental":- return batch.is_first_ever_sync- return False---def _plan_batch_operation(- conn: psycopg.Connection[Any],- batch: PendingBatch,- *,- duckgres_schema: str,- duckgres_table: str,-) -> BatchApplyOperation:- if _should_replace_table(batch):- return BatchApplyOperation(kind="replace")-- if not _table_exists(conn, duckgres_schema, duckgres_table):- return BatchApplyOperation(kind="create")-- if batch.sync_type == "incremental":- if batch.is_first_ever_sync:- return BatchApplyOperation(kind="insert", ensure_target_columns=True)-- primary_keys = _primary_keys(batch)- if not primary_keys:- raise PermanentBatchApplyError("Duckgres incremental batches require primary keys")- return BatchApplyOperation(kind="merge", ensure_target_columns=True, primary_keys=primary_keys)-- if batch.sync_type in ("full_refresh", "append"):- return BatchApplyOperation(kind="insert", ensure_target_columns=True)-- raise PermanentBatchApplyError(f"Unsupported Duckgres sync type: {batch.sync_type}")---# Per-connection cache of tables confirmed to exist: the sink checks existence-# every non-first batch, so cache positive results (a table stays existing for-# the connection's life — the sink never drops tables mid-run). Only positives-# are cached (a table may be created between batches); GC'd with the connection.-_existing_tables: WeakKeyDictionary[psycopg.Connection[Any], set[tuple[str, str]]] = WeakKeyDictionary()---def _table_exists(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str) -> bool:- known = _existing_tables.setdefault(conn, set())- if (duckgres_schema, duckgres_table) in known:- return True- exists = _probe_table_exists(conn, duckgres_schema, duckgres_table)- if exists:- known.add((duckgres_schema, duckgres_table))- return exists---def _probe_table_exists(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str) -> bool:- """Cheap single-table existence probe (autocommit, so a raised error is inert).-- A `LIMIT 0` reference loads only this table's metadata (~0.1-0.6s even under- concurrent snapshot commits); the former `information_schema.tables` check- re-materialized the whole catalog (~48s under load on a large catalog).- duckgres reports a missing table as a generic XX000 carrying DuckDB's stable- "Table with name X does not exist" catalog message. Match that specifically —- a bare "does not exist" would also swallow a missing schema/catalog/secret,- wrongly routing a real failure to the create path. Anything else propagates.- """- try:- conn.execute(- sql.SQL("SELECT 1 FROM {}.{} LIMIT 0").format(- sql.Identifier(duckgres_schema), sql.Identifier(duckgres_table)- )- )- return True- except psycopg.Error as err:- message = str(err).lower()- if "table with name" in message and "does not exist" in message:- return False- raise---def _replace_table(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, paths: list[str]) -> None:- conn.execute(- sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(duckgres_table),- _read_parquet_expr(paths),- )- )---def _create_table_from_parquet(- conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, paths: list[str]-) -> None:- conn.execute(- sql.SQL("CREATE TABLE {}.{} AS SELECT * FROM {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(duckgres_table),- _read_parquet_expr(paths),- )- )---def _ensure_duckgres_apply_table(conn: psycopg.Connection[Any], duckgres_schema: str) -> None:- conn.execute(- sql.SQL(- """- CREATE TABLE IF NOT EXISTS {}.{} (- schema_id VARCHAR NOT NULL,- run_uuid VARCHAR NOT NULL,- batch_index BIGINT NOT NULL,- batch_id VARCHAR NOT NULL,- applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),- PRIMARY KEY (schema_id, run_uuid, batch_index)- )- """- ).format(- sql.Identifier(duckgres_schema),- sql.Identifier(DUCKGRES_APPLY_TABLE),- )- )---def _has_duckgres_batch_applied(conn: psycopg.Connection[Any], duckgres_schema: str, *, batch: PendingBatch) -> bool:- cursor = conn.execute(- sql.SQL(- """- SELECT 1- FROM {}.{}- WHERE schema_id = %s- AND run_uuid = %s- AND batch_index = %s- LIMIT 1- """- ).format(- sql.Identifier(duckgres_schema),- sql.Identifier(DUCKGRES_APPLY_TABLE),- ),- [batch.schema_id, batch.run_uuid, batch.batch_index],- )- return cursor.fetchone() is not None---def _mark_duckgres_batch_applied(conn: psycopg.Connection[Any], duckgres_schema: str, *, batch: PendingBatch) -> None:- cursor = conn.execute(- sql.SQL(- """- -- applied_at is set explicitly: DuckLake does not apply the column's- -- DEFAULT now() on insert (unlike Postgres), so omitting it writes NULL- -- and trips the NOT NULL constraint.- INSERT INTO {}.{} (schema_id, run_uuid, batch_index, batch_id, applied_at)- VALUES (%s, %s, %s, %s, now())- ON CONFLICT (schema_id, run_uuid, batch_index) DO NOTHING- """- ).format(- sql.Identifier(duckgres_schema),- sql.Identifier(DUCKGRES_APPLY_TABLE),- ),- [batch.schema_id, batch.run_uuid, batch.batch_index, batch.id],- )- if not cursor.rowcount:- # The marker insert shares the data write's transaction, so raising here- # rolls the data write back: the marker table is the arbiter that makes- # concurrent double-apply impossible regardless of advisory-lock state.- raise DuckgresBatchAlreadyAppliedError(- f"batch {batch.schema_id}/{batch.run_uuid}/{batch.batch_index} already applied"- )---def _prune_duckgres_apply_markers(conn: psycopg.Connection[Any], duckgres_schema: str) -> None:- """Opportunistic retention for the duckgres-side marker table (runs at batch 0)."""- try:- conn.execute(- sql.SQL("DELETE FROM {}.{} WHERE applied_at < now() - INTERVAL {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(DUCKGRES_APPLY_TABLE),- sql.Literal(f"{APPLY_MARKER_RETENTION_DAYS} days"),- )- )- except Exception:- # Retention is best-effort; never fail a batch over it.- logger.exception("duckgres_apply_marker_prune_failed", duckgres_schema=duckgres_schema)---def _read_parquet_columns(conn: psycopg.Connection[Any], paths: list[str]) -> list[str]:- return [column.name for column in _read_parquet_schema(conn, paths)]---def _read_parquet_schema(- conn: psycopg.Connection[Any], paths: list[str], *, union_by_name: bool = False-) -> list[DuckgresColumn]:- cursor = conn.execute(- sql.SQL("DESCRIBE SELECT * FROM {} LIMIT 0").format(_read_parquet_expr(paths, union_by_name=union_by_name))- )- rows = cursor.fetchall()- if not rows:- raise ValueError("Duckgres could not read parquet column metadata")- return [DuckgresColumn(name=str(row[0]), type_sql=str(row[1])) for row in rows]---def _ensure_target_columns(- conn: psycopg.Connection[Any],- duckgres_schema: str,- duckgres_table: str,- parquet_schema: list[DuckgresColumn],-) -> None:- cursor = conn.execute(- """- SELECT column_name- FROM information_schema.columns- WHERE table_schema = %s- AND table_name = %s- """,- [duckgres_schema, duckgres_table],- )- existing_columns = {str(row[0]) for row in cursor.fetchall()}-- for column in parquet_schema:- if column.name in existing_columns:- continue- conn.execute(- sql.SQL("ALTER TABLE {}.{} ADD COLUMN {} {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(duckgres_table),- sql.Identifier(column.name),- sql.SQL(column.type_sql),- )- )---def _apply_batch_operation(- conn: psycopg.Connection[Any],- operation: BatchApplyOperation,- *,- duckgres_schema: str,- duckgres_table: str,- paths: list[str],- columns: list[str],-) -> None:- if operation.kind == "replace":- _replace_table(conn, duckgres_schema, duckgres_table, paths)- return- if operation.kind == "create":- _create_table_from_parquet(conn, duckgres_schema, duckgres_table, paths)- return- if operation.kind == "insert":- _insert_batch(conn, duckgres_schema, duckgres_table, paths, columns)- return- if operation.kind == "merge":- if operation.primary_keys is None:- raise PermanentBatchApplyError("Duckgres merge operation requires primary keys")- _merge_batch(conn, duckgres_schema, duckgres_table, paths, columns, operation.primary_keys)- return- raise PermanentBatchApplyError(f"Unsupported Duckgres apply operation: {operation.kind}")---def _insert_batch(- conn: psycopg.Connection[Any],- duckgres_schema: str,- duckgres_table: str,- paths: list[str],- columns: list[str],- *,- union_by_name: bool = False,-) -> None:- insert_columns = sql.SQL(", ").join(sql.Identifier(column) for column in columns)- select_columns = sql.SQL(", ").join(sql.SQL("source.{}").format(sql.Identifier(column)) for column in columns)- conn.execute(- sql.SQL("INSERT INTO {}.{} ({}) SELECT {} FROM {} AS source").format(- sql.Identifier(duckgres_schema),- sql.Identifier(duckgres_table),- insert_columns,- select_columns,- _read_parquet_expr(paths, union_by_name=union_by_name),- )- )---def _merge_batch(- conn: psycopg.Connection[Any],- duckgres_schema: str,- duckgres_table: str,- paths: list[str],- columns: list[str],- primary_keys: list[str],-) -> None:- normalized_primary_keys = [NamingConvention.normalize_identifier(key) for key in primary_keys]- missing_keys = [key for key in normalized_primary_keys if key not in columns]- if missing_keys:- raise PermanentBatchApplyError(f"Duckgres incremental batch missing primary keys: {missing_keys}")-- update_columns = [column for column in columns if column not in normalized_primary_keys]- if not update_columns:- update_columns = [normalized_primary_keys[0]]- on_clause = sql.SQL(" AND ").join(- sql.SQL("source.{} = target.{}").format(sql.Identifier(key), sql.Identifier(key))- for key in normalized_primary_keys- )- update_clause = sql.SQL(", ").join(- sql.SQL("{} = source.{}").format(sql.Identifier(column), sql.Identifier(column)) for column in update_columns- )- insert_columns = sql.SQL(", ").join(sql.Identifier(column) for column in columns)- insert_values = sql.SQL(", ").join(sql.SQL("source.{}").format(sql.Identifier(column)) for column in columns)-- matched_clause = sql.SQL("WHEN MATCHED THEN UPDATE SET {}").format(update_clause)-- query = sql.SQL(- """- MERGE INTO {}.{} AS target- USING {} AS source- ON {}- {}- WHEN NOT MATCHED THEN INSERT ({}) VALUES ({})- """- ).format(- sql.Identifier(duckgres_schema),- sql.Identifier(duckgres_table),- _read_parquet_expr(paths),- on_clause,- matched_clause,- insert_columns,- insert_values,- )- conn.execute(query)---def _primary_keys(batch: PendingBatch) -> list[str]:- raw = batch.metadata.get("primary_keys")- if not isinstance(raw, list):- return []- return [str(key) for key in raw]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.pydeleted file mode 100644index d5a33aa752b3..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py+++ /dev/null@@ -1,674 +0,0 @@-import uuid-from dataclasses import replace-from datetime import timedelta-from types import SimpleNamespace-from typing import Any, cast--import pytest-from freezegun import freeze_time-from unittest.mock import MagicMock, Mock, patch--from django.utils import timezone--import psycopg--from posthog.models import Organization, Team--from products.managed_warehouse.backend.facade.contracts import (- DuckgresSinkState,- DuckgresSinkStateCreateInput,- DuckgresSinkStateRecord,-)-from products.managed_warehouse.backend.facade.testing import (- count_sink_states,- create_sink_state,- get_sink_state,- list_sink_states,- replace_sink_state,- sink_state_exists,-)-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema-from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource-from products.warehouse_sources.backend.models.table import DataWarehouseTable-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import (- backfill as backfill_module,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (- _bootstrap_state_rows,- _plan_pending,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (- backfill_run_uuid,- enqueue_chunks,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (- CHUNK_TARGET_BYTES,- BackfillChunk,- _committed_batch_keys,- _group_files_into_chunks,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (- RETIRE_KIND_SUPERSEDED_BY_REPLACE,-)-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import create_job_model--_State = DuckgresSinkState---def _sink_state(team: Team, state: DuckgresSinkState) -> DuckgresSinkStateRecord:- return create_sink_state(DuckgresSinkStateCreateInput(team_id=team.id, schema_id=uuid.uuid4(), state=state))---def _refresh_state(state: DuckgresSinkStateRecord) -> DuckgresSinkStateRecord:- refreshed = get_sink_state(state.id)- assert refreshed is not None- return refreshed---def _replace_state(state: DuckgresSinkStateRecord, **changes: Any) -> DuckgresSinkStateRecord:- state = replace(state, **changes)- replace_sink_state(state)- return state---class TestChunkGrouping:- def test_groups_small_files_up_to_target(self):- files = [(f"s3://b/f{i}.parquet", CHUNK_TARGET_BYTES // 4, 10) for i in range(10)]-- chunks = _group_files_into_chunks(files)-- assert [len(c.paths) for c in chunks] == [4, 4, 2]- assert [c.index for c in chunks] == [0, 1, 2]- assert sum(c.row_count for c in chunks) == 100-- def test_oversized_file_gets_its_own_chunk(self):- files = [- ("s3://b/small.parquet", 100, 1),- ("s3://b/huge.parquet", CHUNK_TARGET_BYTES * 3, 1000),- ("s3://b/small2.parquet", 100, 1),- ]-- chunks = _group_files_into_chunks(files)-- # huge file closes the first chunk and lands alone; trailing small file follows- assert len(chunks) == 3- assert chunks[1].paths == ["s3://b/huge.parquet"]-- def test_empty_input(self):- assert _group_files_into_chunks([]) == []---def test_backfill_run_uuid_is_unique_per_planning_attempt():- # The generation nonce is load-bearing: a replan at an UNADVANCED Delta- # version must still produce a fresh, claimable run (the old run's batches- # are terminally failed and would otherwise be reused verbatim).- a = backfill_run_uuid("abc", 7)- b = backfill_run_uuid("abc", 7)- assert a != b- assert a.startswith("duckgres-backfill-abc-v7-g")- assert b.startswith("duckgres-backfill-abc-v7-g")---def test_chunk_dataclass_shape():- c = BackfillChunk(0, ["s3://b/f"], 1, 2)- assert (c.index, c.byte_size, c.row_count) == (0, 1, 2)---def test_bootstrap_state_rows_streams_batches_and_skips_existing(monkeypatch):- # A single team can own far more schemas than fit in one bulk_create, so the- # bootstrap streams and flushes in batches. Force a tiny batch so the schemas- # below straddle a flush boundary — guards against the final partial batch- # being dropped and against the anti-join re-creating rows that already exist.- monkeypatch.setattr(backfill_module, "BOOTSTRAP_BATCH_SIZE", 2)- # The v3-source gate does a network flag eval; stub it on so this test stays- # about the streaming/batching path, not flag resolution.- monkeypatch.setattr(create_job_model, "is_pipeline_v3_enabled", lambda team_id, source_type: True)-- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- source = ExternalDataSource.objects.create(- team_id=team.pk,- source_id=str(uuid.uuid4()),- connection_id=str(uuid.uuid4()),- status="Completed",- source_type="Postgres",- )- table = DataWarehouseTable.objects.create(name="t", format="Parquet", team=team, url_pattern="https://b.s3/data/*")-- def _schema(name, sync_type, *, with_table):- return ExternalDataSchema.objects.create(- team_id=team.pk, source=source, name=name, sync_type=sync_type, table=table if with_table else None- )-- # Only incremental-with-a-table needs priming; the rest land straight in PRIMED.- needs_priming = _schema("incremental", ExternalDataSchema.SyncType.INCREMENTAL, with_table=True)- full_refresh = _schema("full_refresh", ExternalDataSchema.SyncType.FULL_REFRESH, with_table=True)- cdc = _schema("cdc", ExternalDataSchema.SyncType.CDC, with_table=True)- no_table = _schema("no_table", ExternalDataSchema.SyncType.INCREMENTAL, with_table=False)-- _bootstrap_state_rows([team.pk])-- states = {state.schema_id: state.state for state in list_sink_states()}- assert states == {- needs_priming.id: _State.PENDING_BACKFILL,- full_refresh.id: _State.PRIMED,- cdc.id: _State.PRIMED,- no_table.id: _State.PRIMED,- }-- # Re-running must not duplicate or revert anything — the anti-join skips all four.- _bootstrap_state_rows([team.pk])- assert count_sink_states() == 4---def test_committed_batch_keys_filters_to_snapshot_version():- class FakeDeltaTable:- def history(self):- return [- {"version": 12, "run_uuid": "after-snapshot", "batch_index": "0"},- {"version": 11, "run_uuid": "flat-layout", "batch_index": "2"},- {"version": 10, "userMetadata": '{"run_uuid": "nested-layout", "batch_index": "3"}'},- {"version": 9, "operation": "CREATE TABLE"},- {"version": 8, "run_uuid": "bad-batch-index", "batch_index": "nan"},- ]-- assert _committed_batch_keys(FakeDeltaTable(), snapshot_version=11) == [- ("flat-layout", 2),- ("nested-layout", 3),- ]---class TestPlanPendingConcurrencyCaps:- # Caps are patched to explicit values so these stay deterministic if the- # production constants are later tuned. _plan_one is the queue-DB + Delta- # boundary; blocked candidates must never reach it, claimed ones must.-- def test_global_cap_blocks_further_claims(self, monkeypatch):- monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_GLOBAL", 2)- monkeypatch.setattr(backfill_module, "_plan_one", lambda state: pytest.fail("planned past the global cap"))-- busy_team = Team.objects.create(organization=Organization.objects.create(name="busy"), name="t")- for _ in range(2):- _sink_state(busy_team, _State.BACKFILLING)-- candidate = _sink_state(- Team.objects.create(organization=Organization.objects.create(name="new"), name="t"), _State.PENDING_BACKFILL- )-- _plan_pending(team_ids=[candidate.team_id])-- candidate = _refresh_state(candidate)- # Different org, so per-org never blocks it — only the full global budget does.- assert candidate.state == _State.PENDING_BACKFILL-- def test_per_org_cap_blocks_same_org(self, monkeypatch):- monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_PER_ORG", 1)- monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_GLOBAL", 99) # global is not the limiter here- monkeypatch.setattr(backfill_module, "_plan_one", lambda state: pytest.fail("planned past the per-org cap"))-- team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")- _sink_state(team, _State.BACKFILLING)- candidate = _sink_state(team, _State.PENDING_BACKFILL)-- _plan_pending(team_ids=[team.id])-- candidate = _refresh_state(candidate)- assert candidate.state == _State.PENDING_BACKFILL-- def test_under_cap_claims_and_plans(self, monkeypatch):- monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_PER_ORG", 1)- monkeypatch.setattr(backfill_module, "MAX_CONCURRENT_BACKFILLS_GLOBAL", 5)- planned: list = []- monkeypatch.setattr(backfill_module, "_plan_one", lambda state: planned.append(state.id))-- candidate = _sink_state(- Team.objects.create(organization=Organization.objects.create(name="org"), name="t"),- _State.PENDING_BACKFILL,- )-- _plan_pending(team_ids=[candidate.team_id])-- candidate = _refresh_state(candidate)- assert candidate.state == _State.BACKFILLING- assert planned == [candidate.id]---class TestBootstrapV3SourceGate:- # warehouse-pipelines-v3 (is_pipeline_v3_enabled) is the network-flag boundary;- # stub it so the assertion is on which schemas get a state row.- def test_only_v3_sources_are_primed(self, monkeypatch):- from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource-- monkeypatch.setattr(- create_job_model,- "is_pipeline_v3_enabled",- lambda team_id, source_type: source_type == "Postgres",- )-- team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")- v3_source = ExternalDataSource.objects.create(- team=team, source_id="s1", connection_id="c1", source_type="Postgres", status="Running"- )- non_v3_source = ExternalDataSource.objects.create(- team=team, source_id="s2", connection_id="c2", source_type="Stripe", status="Running"- )- v3_schema = ExternalDataSchema.objects.create(team=team, name="pg", source=v3_source)- non_v3_schema = ExternalDataSchema.objects.create(team=team, name="stripe", source=non_v3_source)-- backfill_module._bootstrap_state_rows([team.id])-- primed = {state.schema_id for state in list_sink_states() if state.team_id == team.id}- assert v3_schema.id in primed- assert non_v3_schema.id not in primed---# Stands in for the queue-DB connection in _reconcile_one: the SQL results are-# the boundary; the assertions are on the Django state writes.-class _FakeQueueConn:- def __init__(self, results: list) -> None:- self._results = list(results)-- def execute(self, *args, **kwargs):- row = self._results.pop(0)- return SimpleNamespace(fetchone=lambda: row)---def _fake_conn(results: list) -> psycopg.Connection[Any]:- return cast("psycopg.Connection[Any]", _FakeQueueConn(results))---class TestFailureStreak:- def _team(self) -> Team:- return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")-- def _backdate(self, state: DuckgresSinkStateRecord, seconds: int) -> None:- _replace_state(state, updated_at=timezone.now() - timedelta(seconds=seconds))-- def test_plan_failure_records_streak_and_first_failed_at_once(self, monkeypatch):- monkeypatch.setattr(backfill_module, "_plan_one", Mock(side_effect=RuntimeError("no files in log segment")))- candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)-- _plan_pending(team_ids=[candidate.team_id])- candidate = _refresh_state(candidate)- assert candidate.state == _State.PENDING_BACKFILL- assert candidate.consecutive_failures == 1- assert candidate.first_failed_at is not None- assert "no files in log segment" in (candidate.last_error or "")- streak_started_at = candidate.first_failed_at-- # Second failed attempt: the streak grows but the high-watermark anchor- # must not move — it is the durable "backfill owed since" timestamp.- self._backdate(candidate, seconds=3600) # clear the retry backoff window- _plan_pending(team_ids=[candidate.team_id])- candidate = _refresh_state(candidate)- assert candidate.consecutive_failures == 2- assert candidate.first_failed_at == streak_started_at-- def test_unsupported_table_parks_needs_resync_with_streak(self, monkeypatch):- monkeypatch.setattr(- backfill_module, "_plan_one", Mock(side_effect=backfill_module.BackfillUnsupportedError("deletion vectors"))- )- candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)-- _plan_pending(team_ids=[candidate.team_id])-- candidate = _refresh_state(candidate)- assert candidate.state == _State.NEEDS_RESYNC- assert candidate.consecutive_failures == 1- assert candidate.first_failed_at is not None-- def test_capacity_revert_does_not_start_a_streak(self, monkeypatch):- # Pre-check passes, post-claim re-check trips: the revert is pacing, not- # failure — recording it would misclassify busy-but-healthy orgs.- monkeypatch.setattr(backfill_module, "_org_at_capacity", Mock(side_effect=[False, True]))- monkeypatch.setattr(backfill_module, "_plan_one", Mock(side_effect=AssertionError("must not plan")))- candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)-- _plan_pending(team_ids=[candidate.team_id])-- candidate = _refresh_state(candidate)- assert candidate.state == _State.PENDING_BACKFILL- assert candidate.consecutive_failures == 0- assert candidate.first_failed_at is None-- @freeze_time("2026-01-15T12:00:00Z")- def test_backoff_skips_recent_failure_then_retries_after_window(self, monkeypatch):- plan_one = Mock(side_effect=RuntimeError("still broken"))- monkeypatch.setattr(backfill_module, "_plan_one", plan_one)- candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)- _replace_state(candidate, consecutive_failures=10, first_failed_at=timezone.now())-- # Streak at cap, updated_at fresh: inside the backoff window, no attempt.- _plan_pending(team_ids=[candidate.team_id])- plan_one.assert_not_called()-- # Past the max window (cap * max jitter): retried — backoff delays, never gives up.- self._backdate(candidate, seconds=int(backfill_module.RETRY_BACKOFF_CAP_SECONDS * 1.2) + 1)- _plan_pending(team_ids=[candidate.team_id])- plan_one.assert_called_once()-- @freeze_time("2026-01-15T12:00:00Z")- def test_mark_primed_resets_streak(self):- candidate = _sink_state(self._team(), _State.BACKFILLING)- _replace_state(- candidate,- consecutive_failures=5,- first_failed_at=timezone.now(),- last_error="boom",- backfill_run_uuid="run-1",- )-- backfill_module.mark_primed(str(candidate.schema_id), run_uuid="run-1")-- candidate = _refresh_state(candidate)- assert candidate.state == _State.PRIMED- assert candidate.consecutive_failures == 0- assert candidate.first_failed_at is None- assert candidate.last_error is None-- @freeze_time("2026-01-15T12:00:00Z")- def test_replan_backfill_resets_streak(self):- candidate = _sink_state(self._team(), _State.NEEDS_RESYNC)- _replace_state(candidate, consecutive_failures=5, first_failed_at=timezone.now(), last_error="boom")-- backfill_module.replan_backfill(str(candidate.schema_id))-- candidate = _refresh_state(candidate)- assert candidate.state == _State.PENDING_BACKFILL- assert candidate.consecutive_failures == 0- assert candidate.first_failed_at is None-- @freeze_time("2026-01-15T12:00:00Z")- def test_stuck_gauges_derive_from_state_without_any_batches(self):- # The whole point of the state-derived gauges: a wedged schema stays- # visible with zero rows in the (retention-bounded) batch queue.- team = self._team()- stuck = _sink_state(team, _State.PENDING_BACKFILL)- _replace_state(- stuck,- consecutive_failures=backfill_module.FAILING_THRESHOLD,- first_failed_at=timezone.now() - timedelta(days=20),- )- _sink_state(team, _State.PENDING_BACKFILL) # healthy: not counted-- backfill_module._emit_state_gauge()-- assert backfill_module.STUCK_BACKFILL_GAUGE._value.get() == 1- assert backfill_module.STUCK_BACKFILL_OLDEST_AGE_GAUGE._value.get() == pytest.approx(- timedelta(days=20).total_seconds(), rel=0.01- )-- def test_reconcile_escalates_wedged_run_to_failing_once(self):- # A duckgres 'failed' status is terminal — the run never retries itself,- # so reconcile must classify the schema failing immediately or its- # backlog sits in the pageable healthy bucket forever.- candidate = _sink_state(self._team(), _State.BACKFILLING)- _replace_state(candidate, backfill_run_uuid="bf-run", chunk_count=5, chunks_applied=1)- candidate = _refresh_state(candidate)-- backfill_module._reconcile_one(_fake_conn([(1,), ("chunk exploded", None)]), candidate)-- candidate = _refresh_state(candidate)- assert candidate.state == _State.BACKFILLING- assert candidate.consecutive_failures >= backfill_module.FAILING_THRESHOLD- assert candidate.first_failed_at is not None- assert candidate.last_error == "chunk exploded"- streak_started_at = candidate.first_failed_at- marked_at = candidate.updated_at-- # A steady wedge stops churning the row once recorded (same error,- # streak already at threshold, anchor stamped).- backfill_module._reconcile_one(_fake_conn([(1,), ("chunk exploded", None)]), candidate)- candidate = _refresh_state(candidate)- assert candidate.first_failed_at == streak_started_at- assert candidate.updated_at == marked_at-- def test_reconcile_supersession_is_streak_neutral(self):- # Retirement by a newer live replace run is normal lifecycle, not failure.- candidate = _sink_state(self._team(), _State.BACKFILLING)- _replace_state(candidate, backfill_run_uuid="bf-run", chunk_count=5)- candidate = _refresh_state(candidate)-- backfill_module._reconcile_one(_fake_conn([(0,), ("superseded", RETIRE_KIND_SUPERSEDED_BY_REPLACE)]), candidate)-- candidate = _refresh_state(candidate)- assert candidate.state == _State.NEEDS_RESYNC- assert candidate.consecutive_failures == 0- assert candidate.first_failed_at is None-- @freeze_time("2026-01-15T12:00:00Z")- def test_reconcile_chunk_progress_resets_streak(self):- # Chunks landing again is forward progress: the streak (and with it the- # failing classification) must end, or a healed schema stays unalerted.- candidate = _sink_state(self._team(), _State.BACKFILLING)- _replace_state(- candidate,- backfill_run_uuid="bf-run",- chunk_count=5,- chunks_applied=1,- snapshot_version=None,- consecutive_failures=4,- first_failed_at=timezone.now(),- )- candidate = _refresh_state(candidate)-- # applied=3 (progress), no failed batch, all 5 chunk rows still present.- backfill_module._reconcile_one(_fake_conn([(3,), None, (5,)]), candidate)-- candidate = _refresh_state(candidate)- assert candidate.chunks_applied == 3- assert candidate.consecutive_failures == 0- assert candidate.first_failed_at is None---# transaction=True: failing_schema_ids calls close_old_connections (thread-entry-# hygiene for the consumer's sync_to_async maintenance calls), which severs the-# TestCase-style transaction-wrapped connection.[email protected]_db(transaction=True)-class TestFailingSchemaClassification:- def test_failing_schema_ids_classification(self):- team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")-- def _state_with(state: DuckgresSinkState, failures: int) -> DuckgresSinkStateRecord:- row = _sink_state(team, state)- return _replace_state(row, consecutive_failures=failures)-- healthy_pending = _state_with(_State.PENDING_BACKFILL, 0)- below_threshold = _state_with(_State.PENDING_BACKFILL, backfill_module.FAILING_THRESHOLD - 1)- failing_pending = _state_with(_State.PENDING_BACKFILL, backfill_module.FAILING_THRESHOLD)- failing_backfilling = _state_with(_State.BACKFILLING, backfill_module.FAILING_THRESHOLD)- parked = _state_with(_State.NEEDS_RESYNC, 0)- # PRIMED is never failing, even with a stale streak left behind.- primed_stale_streak = _state_with(_State.PRIMED, 10)-- assert set(backfill_module.failing_schema_ids([team.id])) == {- str(failing_pending.schema_id),- str(failing_backfilling.schema_id),- str(parked.schema_id),- }- assert backfill_module.failing_schema_ids([]) == []- for row in (healthy_pending, below_threshold, primed_stale_streak):- assert str(row.schema_id) not in backfill_module.failing_schema_ids(None)---class TestGenerationPinnedPromotions:- def _team(self) -> Team:- return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")-- def _backfilling_state(self, run_uuid: str | None, chunk_count: int = 2) -> DuckgresSinkStateRecord:- return create_sink_state(- DuckgresSinkStateCreateInput(- team_id=self._team().id,- schema_id=uuid.uuid4(),- state=_State.BACKFILLING,- backfill_run_uuid=run_uuid,- chunk_count=chunk_count,- chunks_applied=0,- )- )-- def test_mark_primed_ignores_stale_generation(self):- # A replan can retire run R1 and plan R2 while R1's final swap is still- # committing; R1's late mark_primed must not promote R2's row.- row = self._backfilling_state("run-r2")-- backfill_module.mark_primed(str(row.schema_id), run_uuid="run-r1", chunks_applied=2)- row = _refresh_state(row)- assert row.state == _State.BACKFILLING-- backfill_module.mark_primed(str(row.schema_id), run_uuid="run-r2", chunks_applied=2)- row = _refresh_state(row)- assert row.state == _State.PRIMED- assert row.chunks_applied == 2-- def test_reconcile_promotion_ignores_stale_generation(self):- # The reconciler's applied-count evidence belongs to the run it read at- # the top of the pass; a replan swapping generations mid-pass must not- # be promoted on the old run's counts.- row = self._backfilling_state("run-r1")- stale_snapshot = _refresh_state(row)- _replace_state(row, backfill_run_uuid="run-r2")-- conn = MagicMock()- conn.execute.return_value.fetchone.return_value = (stale_snapshot.chunk_count,)- backfill_module._reconcile_one(conn, stale_snapshot)-- row = _refresh_state(row)- assert row.state == _State.BACKFILLING- assert row.backfill_run_uuid == "run-r2"-- def test_plan_one_defers_while_replace_run_inflight(self):- team = self._team()- source = ExternalDataSource.objects.create(- team=team, source_id="s", connection_id="c", source_type="Stripe", status="Running"- )- schema = ExternalDataSchema.objects.create(team=team, source=source, name="customers")- row = create_sink_state(- DuckgresSinkStateCreateInput(- team_id=team.id,- schema_id=schema.id,- state=_State.BACKFILLING,- backfill_run_uuid=None,- )- )-- with (- patch.object(backfill_module, "_has_inflight_replace_run", return_value=True),- patch.object(backfill_module, "resolve_snapshot_plan") as resolve,- patch.object(backfill_module.psycopg, "connect") as connect,- ):- connect.return_value.__enter__.return_value = MagicMock()- backfill_module._plan_one(row)-- resolve.assert_not_called()- row = _refresh_state(row)- assert row.backfill_run_uuid is None- assert row.state == _State.BACKFILLING---class TestDeletedSchemaPurge:- def _fixture(self, deleted: bool, run_uuid: str | None = "run-1"):- team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")- source = ExternalDataSource.objects.create(- team=team, source_id="s", connection_id="c", source_type="Stripe", status="Running"- )- schema = ExternalDataSchema.objects.create(team=team, source=source, name="customers", deleted=deleted)- state = create_sink_state(- DuckgresSinkStateCreateInput(- team_id=team.id,- schema_id=schema.id,- state=_State.BACKFILLING,- backfill_run_uuid=run_uuid,- )- )- return schema, state-- def test_purge_retires_run_and_drops_state_for_deleted_schema(self):- _, state = self._fixture(deleted=True)- conn = MagicMock()- with patch.object(backfill_module, "retire_backfill_run") as retire:- backfill_module._purge_deleted_schema_states(conn, None)- retire.assert_called_once_with(conn, run_uuid="run-1")- assert not sink_state_exists(state.id)-- def test_purge_leaves_live_schemas_untouched(self):- _, state = self._fixture(deleted=False)- conn = MagicMock()- with patch.object(backfill_module, "retire_backfill_run") as retire:- backfill_module._purge_deleted_schema_states(conn, None)- retire.assert_not_called()- assert sink_state_exists(state.id)-- def test_plan_one_skips_deleted_schema(self):- _, state = self._fixture(deleted=True, run_uuid=None)- with (- patch.object(backfill_module, "resolve_snapshot_plan") as resolve,- patch.object(backfill_module.psycopg, "connect") as connect,- ):- backfill_module._plan_one(state)- resolve.assert_not_called()- connect.assert_not_called()---class TestEnqueueLockTimeout:- def test_lock_timeout_skips_replay_and_resets(self):- conn = MagicMock()-- def execute(query, *args, **kwargs):- if "pg_advisory_lock" in str(query):- raise psycopg.errors.LockNotAvailable()- return MagicMock()-- conn.execute.side_effect = execute- assert enqueue_chunks(conn, MagicMock(), "run-x", []) == 0- executed = [str(call.args[0]) for call in conn.execute.call_args_list]- assert any("SET lock_timeout" in query for query in executed)- assert any("RESET lock_timeout" in query for query in executed)- assert not any("INSERT INTO" in query for query in executed)---# transaction=True: mark_schema_diverged does thread-entry close_old_connections-# (it is called from the consumer via sync_to_async), which severs the-# TestCase-style transaction-wrapped connection.[email protected]_db(transaction=True)-class TestMarkSchemaDiverged:- def _team(self) -> Team:- return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")-- def test_primed_schema_parks_as_failing_needs_resync(self):- row = _sink_state(self._team(), _State.PRIMED)-- backfill_module.mark_schema_diverged(str(row.schema_id), run_uuid="run-x", error="poison batch")-- row = _refresh_state(row)- assert row.state == _State.NEEDS_RESYNC- assert row.consecutive_failures >= backfill_module.FAILING_THRESHOLD- assert row.first_failed_at is not None- assert "run-x" in (row.last_error or "")-- # Second terminal failure must not clobber the streak anchor or error:- # the CAS is PRIMED-only.- anchor = row.first_failed_at- backfill_module.mark_schema_diverged(str(row.schema_id), run_uuid="run-y", error="later failure")- row = _refresh_state(row)- assert row.first_failed_at == anchor- assert "run-x" in (row.last_error or "")-- def test_non_primed_states_are_untouched(self):- # BACKFILLING failures are the reconciler's to escalate; a pending- # schema has no divergence to record.- team = self._team()- for state in (_State.BACKFILLING, _State.PENDING_BACKFILL):- row = _sink_state(team, state)-- backfill_module.mark_schema_diverged(str(row.schema_id), run_uuid="run-x", error="boom")-- row = _refresh_state(row)- assert row.state == state- assert row.consecutive_failures == 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill_snapshot.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill_snapshot.pydeleted file mode 100644index f15da7ceb02a..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill_snapshot.py+++ /dev/null@@ -1,201 +0,0 @@-import uuid-from types import SimpleNamespace--from unittest.mock import patch--from django.test import SimpleTestCase, override_settings--from parameterized import parameterized--from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema-from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource-from products.warehouse_sources.backend.models.table import DataWarehouseTable-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import backfill_snapshot-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (- delta_table_uri,-)--_SCHEMA_ID = uuid.UUID("0190c6a4-6641-0000-0f7a-d9482771b742")---@override_settings(BUCKET_URL="s3://test-bucket/dlt")-class TestDeltaTableUri(SimpleTestCase):- def _schema(self, name: str, leaf: str | None) -> ExternalDataSchema:- # Built in memory (no save): exercises the real normalized_name and- # folder_path. leaf=None models a schema with no catalog table yet.- schema = ExternalDataSchema(id=_SCHEMA_ID, team_id=1, name=name)- schema.source = ExternalDataSource(source_type="Postgres")- if leaf is None:- schema.table = None- else:- url = f"https://bucket.s3.amazonaws.com/dlt/{schema.folder_path()}/{leaf}"- schema.table = DataWarehouseTable(url_pattern=url)- return schema-- @parameterized.expand(- [- # Schema-qualified Postgres source: the loader wrote the Delta folder- # under the unqualified table name, but normalized_name keeps the- # "public_" qualifier. Reading normalized_name pointed the backfill at- # a prefix with no _delta_log ("No files in log segment").- ("schema_qualified", "public.posthog_hogfunction", "posthog_hogfunction/", "posthog_hogfunction"),- # Unqualified name: folder and normalized_name already agree.- (- "unqualified",- "campaign_performance_report",- "campaign_performance_report/",- "campaign_performance_report",- ),- # url_pattern may carry a trailing glob token instead of a bare slash.- ("glob_suffix", "public.posthog_team", "posthog_team/*", "posthog_team"),- ]- )- def test_uri_folder_comes_from_url_pattern_not_normalized_name(- self, _name: str, schema_name: str, leaf: str, expected_leaf: str- ) -> None:- schema = self._schema(schema_name, leaf)-- uri = delta_table_uri(schema)-- assert uri == f"s3://test-bucket/dlt/{schema.folder_path()}/{expected_leaf}"-- def test_falls_back_to_normalized_name_when_no_table(self) -> None:- schema = self._schema("public.posthog_hogfunction", leaf=None)-- uri = delta_table_uri(schema)-- assert uri == f"s3://test-bucket/dlt/{schema.folder_path()}/{schema.normalized_name}"-- def test_injected_url_pattern_leaf_cannot_escape_schema_prefix(self) -> None:- # url_pattern is a user-writable field. A leaf crafted with encoded- # separators (percent-encoded slashes survive split("/") as one segment)- # must not let the backfill target a prefix outside the schema's folder.- schema = self._schema("public.posthog_hogfunction", leaf="..%2f..%2fteam_2_postgres_secret%2fusers")-- uri = delta_table_uri(schema)-- prefix = f"s3://test-bucket/dlt/{schema.folder_path()}/"- assert uri.startswith(prefix)- leaf = uri[len(prefix) :]- assert "/" not in leaf and "." not in leaf and "%" not in leaf---class _FakeColumn:- def __init__(self, values: list) -> None:- self._values = values-- def to_pylist(self) -> list:- return self._values---class _FakeAddActions:- def __init__(self, file_count: int = 1) -> None:- self._file_count = file_count-- def column(self, name: str) -> _FakeColumn:- return {- "path": _FakeColumn([f"f{i}.parquet" for i in range(self._file_count)]),- "size_bytes": _FakeColumn([100] * self._file_count),- "num_records": _FakeColumn([10] * self._file_count),- }[name]---class _FakeDeltaTable:- # Stands in for deltalake.DeltaTable: counts real constructions so the- # cache test can assert a pinned version's Delta log is read only once.- # file_count controls how many add-actions (and thus cache weight) a- # constructed instance reports, letting tests drive the weight budget.- instances = 0- file_count = 1-- def __init__(self, uri: str, version: int | None = None, storage_options: dict | None = None) -> None:- _FakeDeltaTable.instances += 1- self._version = version if version is not None else 42-- def version(self) -> int:- return self._version-- def protocol(self) -> SimpleNamespace:- return SimpleNamespace(reader_features=[])-- def get_add_actions(self, flatten: bool = True) -> _FakeAddActions:- return _FakeAddActions(_FakeDeltaTable.file_count)-- def history(self) -> list[dict]:- return []---@override_settings(BUCKET_URL="s3://test-bucket/dlt")-class TestResolveSnapshotPlanCaching(SimpleTestCase):- # The reconciler re-resolves the same already-pinned snapshot_version on- # every tick until a backfill drains; without a cache each call re-reads- # the whole Delta commit log from S3 (dt.history() has no checkpoint- # shortcut), which for a large table can trip S3 rate limiting.- def setUp(self) -> None:- backfill_snapshot._pinned_snapshot_plan_cache.clear()- backfill_snapshot._pinned_snapshot_plan_cache_weight = 0- _FakeDeltaTable.instances = 0- _FakeDeltaTable.file_count = 1-- def _schema(self) -> ExternalDataSchema:- schema = ExternalDataSchema(id=_SCHEMA_ID, team_id=1, name="orders")- schema.source = ExternalDataSource(source_type="Postgres")- schema.table = None- return schema-- def test_pinned_version_is_resolved_once_across_repeated_calls(self) -> None:- schema = self._schema()-- with patch("deltalake.DeltaTable", _FakeDeltaTable):- first = backfill_snapshot.resolve_snapshot_plan(schema, version=5)- second = backfill_snapshot.resolve_snapshot_plan(schema, version=5)-- assert _FakeDeltaTable.instances == 1- assert first == second-- def test_different_pinned_versions_are_each_resolved(self) -> None:- schema = self._schema()-- with patch("deltalake.DeltaTable", _FakeDeltaTable):- backfill_snapshot.resolve_snapshot_plan(schema, version=5)- backfill_snapshot.resolve_snapshot_plan(schema, version=6)-- assert _FakeDeltaTable.instances == 2-- def test_unpinned_head_version_is_never_cached(self) -> None:- schema = self._schema()-- with patch("deltalake.DeltaTable", _FakeDeltaTable):- backfill_snapshot.resolve_snapshot_plan(schema)- backfill_snapshot.resolve_snapshot_plan(schema)-- assert _FakeDeltaTable.instances == 2-- def test_plan_exceeding_weight_budget_is_never_cached(self) -> None:- # A single table's plan can carry an unbounded number of files/commit- # keys — a table big enough to exceed the whole cache's budget on its- # own must not be retained at all, or one tenant's giant table could- # make the cache hold an unbounded amount indefinitely.- with patch.object(backfill_snapshot, "_PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT", 10):- _FakeDeltaTable.file_count = 11- schema = self._schema()-- with patch("deltalake.DeltaTable", _FakeDeltaTable):- backfill_snapshot.resolve_snapshot_plan(schema, version=5)- backfill_snapshot.resolve_snapshot_plan(schema, version=5)-- assert _FakeDeltaTable.instances == 2- assert len(backfill_snapshot._pinned_snapshot_plan_cache) == 0-- def test_cache_evicts_oldest_entry_once_weight_budget_exceeded(self) -> None:- with patch.object(backfill_snapshot, "_PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT", 10):- _FakeDeltaTable.file_count = 6- schema = self._schema()-- with patch("deltalake.DeltaTable", _FakeDeltaTable):- backfill_snapshot.resolve_snapshot_plan(schema, version=1) # weight 6, fits- backfill_snapshot.resolve_snapshot_plan(schema, version=2) # weight 6: evicts v1 (6+6 > 10)- assert _FakeDeltaTable.instances == 2-- backfill_snapshot.resolve_snapshot_plan(schema, version=1) # re-reads: was evicted- assert _FakeDeltaTable.instances == 3diff --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.pydeleted file mode 100644index 5683994b60a4..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py+++ /dev/null@@ -1,923 +0,0 @@-import time-import uuid-from contextlib import contextmanager-from typing import Any--import pytest-from unittest.mock import AsyncMock, MagicMock, patch--import psycopg-from asgiref.sync import async_to_sync--from posthog.models import Organization, Team--from products.managed_warehouse.backend.facade.contracts import (- CPUnavailableError,- DuckgresSinkState,- DuckgresSinkStateCreateInput,-)-from products.managed_warehouse.backend.facade.testing import create_sink_state, get_sink_state-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (- OwnershipLostError,- PermanentBatchApplyError,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (- ENABLEMENT_REFRESH_SECONDS,- DuckgresBatchConsumer,- DuckgresBatchConsumerAdapter,- DuckgresConsumerConfig,-)-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,-)-from products.warehouse_sources_queue.backend.models import SourceBatchDuckgresStatus---def _make_batch(**overrides: Any) -> PendingBatch:- defaults: dict[str, Any] = {- "id": "00000000-0000-0000-0000-000000000001",- "team_id": 1,- "schema_id": "schema-1",- "source_id": "source-1",- "job_id": "job-1",- "run_uuid": "run-1",- "batch_index": 0,- "s3_path": "s3://bucket/path",- "row_count": 100,- "byte_size": 1024,- "is_final_batch": False,- "total_batches": None,- "total_rows": None,- "sync_type": "full_refresh",- "cumulative_row_count": 0,- "resource_name": "test_resource",- "is_resume": False,- "is_first_ever_sync": False,- "metadata": {},- "latest_attempt": 0,- }- defaults.update(overrides)- return PendingBatch(**defaults)---def _make_consumer(max_attempts: int = 3, **kwargs) -> DuckgresBatchConsumer:- config = DuckgresConsumerConfig(- database_url="postgres://unused:unused@localhost/unused",- max_attempts=max_attempts,- **kwargs,- )- consumer = DuckgresBatchConsumer(config=config, process_batch=AsyncMock())- consumer._poll_conn = _make_healthy_conn()- consumer._recovery_conn = _make_healthy_conn()- return consumer---def _make_healthy_conn(closed: bool = False, broken: bool = False) -> AsyncMock:- # closed/broken must be real booleans, otherwise _ensure_*_conn sees a dead conn and dials the fake database_url.- conn = AsyncMock()- conn.closed = closed- conn.broken = broken- return conn---class TestDuckgresProcessSingle:- @pytest.mark.asyncio- async def test_adapter_forwards_empty_error_response_explicitly(self):- consumer = _make_consumer()- update_status_calls: list[dict[str, Any]] = []-- async def track_status(conn, **kwargs):- update_status_calls.append(kwargs)- return True-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",- new_callable=AsyncMock,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",- new_callable=AsyncMock,- return_value=True,- ),- ):- await consumer._process_single(_make_batch(is_final_batch=True))-- assert update_status_calls[0]["error_response"] is None- assert update_status_calls[1]["error_response"] is None-- @pytest.mark.asyncio- async def test_success_updates_status_and_marks_applied(self):- consumer = _make_consumer()- states: list[str] = []-- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):- states.append(job_state)- return True-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",- new_callable=AsyncMock,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",- new_callable=AsyncMock,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",- new_callable=AsyncMock,- ) as mock_mark,- ):- await consumer._process_single(_make_batch())-- assert states == [SourceBatchDuckgresStatus.State.EXECUTING, SourceBatchDuckgresStatus.State.SUCCEEDED]- mock_mark.assert_called_once()-- @pytest.mark.asyncio- async def test_final_marker_requires_existing_apply_and_does_not_process(self):- consumer = _make_consumer()- consumer._process_batch = AsyncMock()-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",- new_callable=AsyncMock,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- new_callable=AsyncMock,- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",- new_callable=AsyncMock,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",- new_callable=AsyncMock,- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",- new_callable=AsyncMock,- ) as mock_mark,- ):- await consumer._process_single(_make_batch(is_final_batch=True))-- consumer._process_batch.assert_not_called()- mock_mark.assert_not_called()-- @pytest.mark.asyncio- async def test_error_sets_waiting_retry(self):- consumer = _make_consumer(max_attempts=3)- consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))- states: list[str] = []-- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):- states.append(job_state)- return True-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",- new_callable=AsyncMock,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",- new_callable=AsyncMock,- return_value=False,- ),- ):- await consumer._process_single(_make_batch())-- assert states == [SourceBatchDuckgresStatus.State.EXECUTING, SourceBatchDuckgresStatus.State.WAITING_RETRY]-- @pytest.mark.asyncio- async def test_max_attempts_exceeded_fails_duckgres_run_only(self):- consumer = _make_consumer(max_attempts=3)-- with patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail:- await consumer._process_single(_make_batch(latest_attempt=3))-- mock_fail.assert_called_once()---class TestDuckgresEnablementGating:- @pytest.mark.asyncio- async def test_enabled_team_ids_refresh_uses_connection_safe_wrapper(self):- """The refresh crosses from the asyncio poll loop into a worker thread; a bare- sync_to_async never recovers a connection killed by the DB/proxy since the last- refresh, so this must go through database_sync_to_async_pool instead."""- adapter = DuckgresBatchConsumerAdapter()-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.database_sync_to_async_pool",- ) as mock_wrapper:- mock_wrapper.return_value = AsyncMock(return_value=None)- await adapter._enabled_team_ids()-- mock_wrapper.assert_called_once_with(duckgres_sink_enablement)-- @pytest.mark.asyncio- async def test_control_plane_blip_keeps_cached_teams_without_capture_or_retry_storm(self):- """A transient control-plane blip is expected and self-healing: keep the cached- team set, don't report it to error tracking, and re-arm the refresh throttle so- the next poll doesn't re-hit the struggling control plane every ~2s cycle."""- adapter = DuckgresBatchConsumerAdapter()- adapter._team_ids = [7, 8]- # A timestamp older than the refresh window forces the refresh attempt below.- adapter._team_ids_fetched_at = time.monotonic() - (ENABLEMENT_REFRESH_SECONDS + 1)-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.database_sync_to_async_pool",- ) as mock_wrapper,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.capture_exception",- ) as mock_capture,- ):- mock_wrapper.return_value = AsyncMock(side_effect=CPUnavailableError("cp down"))- team_ids = await adapter._enabled_team_ids()-- assert team_ids == [7, 8]- mock_capture.assert_not_called()- assert adapter._team_ids_fetched_at is not None- assert time.monotonic() - adapter._team_ids_fetched_at < ENABLEMENT_REFRESH_SECONDS-- @pytest.mark.asyncio- async def test_fetch_returns_empty_without_querying_when_no_teams_enabled(self):- adapter = DuckgresBatchConsumerAdapter()- adapter._team_ids = []- adapter._team_ids_fetched_at = time.monotonic()- conn = _make_healthy_conn()-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",- new_callable=AsyncMock,- ) as mock_fetch:- batches = await adapter.fetch_and_lock(- conn,- limit=50,- retry_backoff_base_seconds=0,- owner_token="test-owner",- lease_ttl_seconds=300,- max_groups=16,- exclude_groups=[],- )-- assert batches == []- mock_fetch.assert_not_called()-- @pytest.mark.asyncio- async def test_fetch_passes_team_ids_and_runs_maintenance(self):- adapter = DuckgresBatchConsumerAdapter()- adapter._team_ids = [1, 2]- adapter._team_ids_fetched_at = time.monotonic()- conn = _make_healthy_conn()-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",- new_callable=AsyncMock,- return_value=[],- ) as mock_fetch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",- new_callable=AsyncMock,- return_value=0,- ) as mock_supersede,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",- new_callable=AsyncMock,- 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",- ) as mock_planner,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_blocked_schema_ids",- return_value=["blocked-schema"],- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_failing_schema_ids",- return_value=[],- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_eligible_schema_ids",- return_value=["eligible-schema"],- ),- ):- await adapter.fetch_and_lock(- conn,- limit=50,- retry_backoff_base_seconds=30,- owner_token="test-owner",- lease_ttl_seconds=300,- max_groups=16,- exclude_groups=[],- )-- assert mock_fetch.call_args[1]["team_ids"] == [1, 2]- assert mock_fetch.call_args[1]["retry_backoff_base_seconds"] == 30- assert mock_fetch.call_args[1]["blocked_schema_ids"] == ["blocked-schema"]- assert mock_fetch.call_args[1]["eligible_schema_ids"] == ["eligible-schema"]- assert mock_fetch.call_args[1]["owner_token"] == "test-owner"- assert mock_fetch.call_args[1]["lease_ttl_seconds"] == 300- assert mock_fetch.call_args[1]["max_groups"] == 16- mock_supersede.assert_called_once()- mock_backlog.assert_called_once()- mock_planner.assert_called_once_with([1, 2])-- @pytest.mark.asyncio- async def test_fetch_claims_nothing_until_planner_succeeds(self):- adapter = DuckgresBatchConsumerAdapter()- adapter._team_ids = [1]- adapter._team_ids_fetched_at = time.monotonic()- conn = _make_healthy_conn()-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",- new_callable=AsyncMock,- ) as mock_fetch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",- new_callable=AsyncMock,- return_value=0,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",- new_callable=AsyncMock,- 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",- side_effect=RuntimeError("app DB down"),- ),- ):- batches = await adapter.fetch_and_lock(- conn,- limit=50,- retry_backoff_base_seconds=0,- owner_token="test-owner",- lease_ttl_seconds=300,- max_groups=16,- exclude_groups=[],- )-- assert batches == []- mock_fetch.assert_not_called()-- @pytest.mark.asyncio- async def test_fetch_claims_nothing_until_eligible_list_ready(self):- # Prod fail-closed: even with the block list computed, an uncomputed v3- # allow-list must halt claiming so non-v3 source types can't be applied.- adapter = DuckgresBatchConsumerAdapter()- adapter._team_ids = [1]- adapter._team_ids_fetched_at = time.monotonic()- conn = _make_healthy_conn()-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",- new_callable=AsyncMock,- ) as mock_fetch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",- new_callable=AsyncMock,- return_value=0,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",- new_callable=AsyncMock,- 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",- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_blocked_schema_ids",- return_value=["blocked-schema"],- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_failing_schema_ids",- return_value=[],- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_eligible_schema_ids",- side_effect=RuntimeError("flag eval down"),- ),- ):- batches = await adapter.fetch_and_lock(- conn,- limit=50,- retry_backoff_base_seconds=0,- owner_token="test-owner",- lease_ttl_seconds=300,- max_groups=16,- exclude_groups=[],- )-- assert batches == []- mock_fetch.assert_not_called()-- @pytest.mark.asyncio- async def test_fetch_swallows_maintenance_query_timeout_and_skips_planner(self):- # The eligibility-CTE maintenance queries are statement-timeout bounded;- # a timeout (or any transient queue-DB error) must be swallowed so the- # poll loop is neither wedged nor crashed — the planner is skipped and- # nothing is claimed this tick, and the next poll just retries. It's- # also the expected shape of that bound tripping under load, so it- # must not be reported to error tracking as a defect.- adapter = DuckgresBatchConsumerAdapter()- adapter._team_ids = [1, 2]- adapter._team_ids_fetched_at = time.monotonic()- conn = _make_healthy_conn()-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",- new_callable=AsyncMock,- ) as mock_fetch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",- new_callable=AsyncMock,- side_effect=psycopg.errors.QueryCanceled("canceling statement due to statement timeout"),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",- ) as mock_planner,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.capture_exception",- ) as mock_capture,- ):- batches = await adapter.fetch_and_lock(- conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300- )-- assert batches == []- mock_planner.assert_not_called()- mock_fetch.assert_not_called()- mock_capture.assert_not_called()-- @pytest.mark.asyncio- async def test_fetch_reports_unexpected_maintenance_query_error(self):- # A genuine, unexpected maintenance-query failure (not the queue DB's- # own statement timeout) must still be swallowed to protect the poll- # loop, but is worth surfacing to error tracking as a real defect.- adapter = DuckgresBatchConsumerAdapter()- adapter._team_ids = [1, 2]- adapter._team_ids_fetched_at = time.monotonic()- conn = _make_healthy_conn()-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",- new_callable=AsyncMock,- ) as mock_fetch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",- new_callable=AsyncMock,- side_effect=RuntimeError("unexpected queue db failure"),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",- ) as mock_planner,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.capture_exception",- ) as mock_capture,- ):- batches = await adapter.fetch_and_lock(- conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300- )-- assert batches == []- mock_planner.assert_not_called()- mock_fetch.assert_not_called()- mock_capture.assert_called_once()---class TestMidClaimRetire:- @pytest.mark.asyncio- async def test_terminally_retired_batch_aborts_group_without_any_status_write(self):- # A chunk retired mid-claim must abort the whole group with NO status- # write — even an 'executing' row would mask the terminal 'failed'.- consumer = _make_consumer()- consumer._process_batch = AsyncMock()-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",- new_callable=AsyncMock,- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",- new_callable=AsyncMock,- ) as mock_status,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- new_callable=AsyncMock,- ) as mock_status_unless_failed,- pytest.raises(OwnershipLostError),- ):- await consumer._process_single(_make_batch())-- consumer._process_batch.assert_not_called()- mock_status.assert_not_called()- mock_status_unless_failed.assert_not_called()-- @pytest.mark.asyncio- async def test_status_write_blocked_by_terminal_failed_aborts_group(self):- # Any status write blocked by a terminal 'failed' means the batch was- # retired while claimed; stamping a later status would un-retire it.- adapter = DuckgresBatchConsumerAdapter()- conn = _make_healthy_conn()-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- new_callable=AsyncMock,- return_value=False,- ):- with pytest.raises(OwnershipLostError):- await adapter.update_status(- conn,- batch_id="00000000-0000-0000-0000-000000000001",- job_state=SourceBatchDuckgresStatus.State.SUCCEEDED.value,- attempt=1,- )---class TestGroupLeaseRenewal:- @pytest.mark.asyncio- async def test_boundary_ownership_check_extends_the_lease(self):- # Quick chunks never trigger in-batch heartbeats, so the per-batch- # ownership check must renew the lease or a long group loses it mid-run.- adapter = DuckgresBatchConsumerAdapter(lease_ttl_seconds=900)- conn = _make_healthy_conn()-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.renew_lease",- new_callable=AsyncMock,- return_value=True,- ) as mock_renew:- owns = await adapter.verify_advisory_lock(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")-- assert owns is True- assert mock_renew.call_args[1]["lease_ttl_seconds"] == 900---class TestErrorPathOwnershipFencing:- @pytest.mark.asyncio- async def test_error_status_suppressed_when_ownership_lost_mid_batch(self):- # A worker that outlived its lease must abandon with no write, not- # stamp waiting_retry (or fail the run) over the new owner's lifecycle.- consumer = _make_consumer(max_attempts=3)- consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))- lock_conn = _make_healthy_conn()- states: list[str] = []-- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):- states.append(job_state)- return True-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.renew_lease",- new_callable=AsyncMock,- side_effect=[True, False], # start-of-batch check passes; error-path check fails- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",- new_callable=AsyncMock,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",- new_callable=AsyncMock,- return_value=False,- ),- patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,- pytest.raises(OwnershipLostError),- ):- await consumer._process_single(_make_batch(), lock_conn=lock_conn)-- mock_fail.assert_not_called()- assert SourceBatchDuckgresStatus.State.WAITING_RETRY not in states---class TestGroupConnectionFailure:- @pytest.mark.asyncio- async def test_leases_released_when_group_connection_fails(self):- # A failed group-connection open must still release the fetch-time- # leases via the poll conn, or every poll renews them indefinitely.- consumer = _make_consumer()- batches = [_make_batch()]-- with (- patch.object(consumer, "_connect", new_callable=AsyncMock, side_effect=psycopg.OperationalError("no conn")),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.unlock_for_batches",- new_callable=AsyncMock,- ) as mock_unlock,- ):- await consumer._process_group_tracked((1, "schema-1"), batches)-- mock_unlock.assert_called_once_with(consumer._poll_conn, batches=batches, owner_token=consumer._owner_token)---class TestFencedRecoverySweep:- @pytest.mark.asyncio- @pytest.mark.parametrize("fenced_result", [True, False])- async def test_stale_batch_requeued_only_through_the_fenced_write(self, fenced_result):- # The sweep must requeue via the write-time fence and never release- # leases afterwards (the poll loop can reclaim a group mid-sweep).- consumer = _make_consumer(max_attempts=3)- stale_batch = _make_batch(latest_attempt=1)-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_stale_executing",- new_callable=AsyncMock,- return_value=[stale_batch],- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.requeue_stale_executing",- new_callable=AsyncMock,- return_value=fenced_result,- ) as mock_requeue,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.unlock_for_batches",- new_callable=AsyncMock,- ) as mock_unlock,- ):- await consumer._recovery_sweep()-- mock_requeue.assert_called_once()- assert mock_requeue.call_args[1]["grace_seconds"] == consumer._config.recovery_grace_seconds- mock_unlock.assert_not_called()-- @pytest.mark.asyncio- @pytest.mark.parametrize("fenced_result", [True, False])- async def test_exhausted_stale_batch_failed_only_through_the_fenced_write(self, fenced_result):- consumer = _make_consumer(max_attempts=3)- stale_batch = _make_batch(latest_attempt=3)-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_stale_executing",- new_callable=AsyncMock,- return_value=[stale_batch],- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.fail_run_if_stale",- new_callable=AsyncMock,- return_value=fenced_result,- ) as mock_fenced_fail,- patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_unfenced,- ):- await consumer._recovery_sweep()-- mock_fenced_fail.assert_called_once()- assert "max retries exceeded" in mock_fenced_fail.call_args[1]["reason"]- mock_unfenced.assert_not_called()---class TestStuckBatchWatchdog:- @pytest.mark.asyncio- async def test_health_withheld_while_a_batch_is_stuck(self):- reporter = MagicMock()- consumer = _make_consumer(stuck_batch_timeout_seconds=10.0)- consumer._health_reporter = reporter- consumer._inflight_started = {"batch-1": time.monotonic() - 60}-- consumer._report_health()-- reporter.assert_not_called()-- @pytest.mark.asyncio- async def test_health_reported_when_batches_are_fresh_or_absent(self):- reporter = MagicMock()- consumer = _make_consumer(stuck_batch_timeout_seconds=10.0)- consumer._health_reporter = reporter-- consumer._report_health()- consumer._inflight_started = {"batch-1": time.monotonic()}- consumer._report_health()-- assert reporter.call_count == 2---class TestPermanentApplyErrors:- @contextmanager- def _sink_mocks(self, states):- async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):- states.append(job_state)- return True-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status_unless_failed",- side_effect=track_status,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.renew_lease",- new_callable=AsyncMock,- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.is_failed",- new_callable=AsyncMock,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",- new_callable=AsyncMock,- return_value=False,- ),- ):- yield-- @pytest.mark.asyncio- async def test_permanent_error_fails_run_on_first_attempt_and_marks_diverged(self):- # A permanent error must not burn max_attempts waiting_retry cycles,- # and the terminal live-run failure must park the schema (else the- # duckgres table silently diverges from Delta with no signal).- consumer = _make_consumer(max_attempts=3)- consumer._process_batch = AsyncMock(side_effect=PermanentBatchApplyError("unsupported sync type"))- states: list[str] = []-- with (- self._sink_mocks(states),- patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.mark_schema_diverged"- ) as mock_diverged,- ):- await consumer._process_single(_make_batch(latest_attempt=0), lock_conn=_make_healthy_conn())-- mock_fail.assert_called_once()- assert "permanent" in mock_fail.call_args.kwargs.get(- "reason", mock_fail.call_args.args[1] if len(mock_fail.call_args.args) > 1 else ""- )- assert SourceBatchDuckgresStatus.State.WAITING_RETRY not in states- mock_diverged.assert_called_once()-- @pytest.mark.asyncio- async def test_transient_error_still_retries_without_divergence_flip(self):- # Guards against over-eager classification: an ordinary error keeps the- # waiting_retry cycle and must not park the schema.- consumer = _make_consumer(max_attempts=3)- consumer._process_batch = AsyncMock(side_effect=ValueError("connection reset"))- states: list[str] = []-- with (- self._sink_mocks(states),- patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.mark_schema_diverged"- ) as mock_diverged,- ):- await consumer._process_single(_make_batch(latest_attempt=0), lock_conn=_make_healthy_conn())-- mock_fail.assert_not_called()- assert SourceBatchDuckgresStatus.State.WAITING_RETRY in states- mock_diverged.assert_not_called()-- @pytest.mark.asyncio- async def test_backfill_chunk_terminal_failure_does_not_mark_diverged(self):- # Backfill chunks fail against the BACKFILLING state; the reconciler- # escalates those. The divergence flip is for LIVE runs only.- consumer = _make_consumer(max_attempts=3)- consumer._process_batch = AsyncMock(side_effect=PermanentBatchApplyError("malformed chunk metadata"))- states: list[str] = []-- with (- self._sink_mocks(states),- patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.mark_schema_diverged"- ) as mock_diverged,- ):- await consumer._process_single(- _make_batch(- latest_attempt=0, metadata={"duckgres_backfill": {"chunk_paths": ["s3://b/f"], "chunk_count": 1}}- ),- lock_conn=_make_healthy_conn(),- )-- mock_fail.assert_called_once()- mock_diverged.assert_not_called()---# transaction=True: the stamp helper runs via sync_to_async in a separate thread and calls-# close_old_connections, so the row must be committed for that thread to see it.[email protected]_db(transaction=True)-class TestLiveApplyStamp:- def _sink_state(self):- team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")- return create_sink_state(- DuckgresSinkStateCreateInput(- team_id=team.id,- schema_id=uuid.uuid4(),- state=DuckgresSinkState.PRIMED,- )- )-- def test_live_apply_stamps_the_sink_state_row(self) -> None:- # This stamp is the only thing the Data ops Overview tab has for "last applied to- # warehouse" — if the hook stops writing it, the UI silently freezes in time.- state = self._sink_state()- adapter = DuckgresBatchConsumerAdapter()- batch = _make_batch(schema_id=str(state.schema_id))-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",- new=AsyncMock(),- ) as mock_mark_applied:- async_to_sync(adapter.after_batch_processed)(_make_healthy_conn(), batch=batch)-- mock_mark_applied.assert_awaited_once()- state = get_sink_state(state.id)- assert state is not None- assert state.queue_last_applied_at is not None-- @pytest.mark.parametrize(- "overrides",- [- {"metadata": {"duckgres_backfill": True, "chunk_paths": ["s3://b/f"], "chunk_count": 1}},- {"is_final_batch": True},- ],- )- def test_backfill_and_final_batches_do_not_stamp(self, overrides: dict[str, Any]) -> None:- # Backfill chunks report through the chunk counters, and final markers apply nothing;- # stamping either would misreport historical or zero-work processing as a live import.- state = self._sink_state()- adapter = DuckgresBatchConsumerAdapter()- batch = _make_batch(schema_id=str(state.schema_id), **overrides)-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",- new=AsyncMock(),- ):- async_to_sync(adapter.after_batch_processed)(_make_healthy_conn(), batch=batch)-- state = get_sink_state(state.id)- assert state is not None- assert state.queue_last_applied_at is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.pydeleted file mode 100644index bb4a9e441982..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_enablement.py+++ /dev/null@@ -1,176 +0,0 @@-from dataclasses import replace--import pytest-from unittest.mock import MagicMock, patch--from posthog.models import Organization, Team--from products.managed_warehouse.backend.facade.contracts import (- ManagedWarehouseTableNames,- ManagedWarehouseTeamMembership,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import enablement-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (- is_duckgres_sink_team_member,-)---def _cp_row(team: Team, *, backfill_enabled: bool = True) -> ManagedWarehouseTeamMembership:- schema_name = f"team_{team.id}"- return ManagedWarehouseTeamMembership(- team_id=team.id,- organization_id=str(team.organization_id),- schema_name=schema_name,- enabled=True,- backfill_enabled=backfill_enabled,- table_names=ManagedWarehouseTableNames(- events_table=f"events_{schema_name}",- persons_table=f"persons_{schema_name}",- data_imports_schema=f"posthog_data_imports_{schema_name}",- ),- earliest_event_date=None,- )---def _patch_all_rows(rows: list[ManagedWarehouseTeamMembership] | None):- return patch.object(enablement, "list_team_memberships", return_value=rows)---def _patch_budgets(budgets: dict[str, int]):- return patch.object(enablement, "sink_concurrency_by_trusted_organization_ids", return_value=budgets)--[email protected](enablement, "is_dev_mode", return_value=False)[email protected](enablement.posthoganalytics, "feature_enabled")-def test_duckgres_sink_flag_evaluated_locally_with_group_properties(- mock_feature_enabled: MagicMock, _mock_dev: MagicMock-) -> None:- """The duckgres-batch-sink gate must mirror the data-warehouse-scene call:- org+project group properties supplied inline and only-local evaluation."""- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- mock_feature_enabled.return_value = True-- with _patch_all_rows([_cp_row(team)]), _patch_budgets({str(org.id): 4}):- result = enablement.duckgres_sink_enablement()-- assert result is not None- assert result.team_ids == [team.id]-- mock_feature_enabled.assert_called_once_with(- "duckgres-batch-sink",- str(team.uuid),- groups={"organization": str(org.id), "project": str(team.id)},- group_properties={- "organization": {"id": str(org.id)},- "project": {"id": str(team.id), "organization_id": str(org.id)},- },- only_evaluate_locally=True,- send_feature_flag_events=False,- )--[email protected](enablement, "is_dev_mode", return_value=False)[email protected](enablement.posthoganalytics, "feature_enabled")-def test_duckgres_sink_skips_team_when_flag_unresolved_locally(- mock_feature_enabled: MagicMock, _mock_dev: MagicMock-) -> None:- """only_evaluate_locally returns None when the flag can't be resolved; that- falsy value must skip the team, never claim it."""- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- mock_feature_enabled.return_value = None-- with _patch_all_rows([_cp_row(team)]), _patch_budgets({str(org.id): 4}):- result = enablement.duckgres_sink_enablement()-- assert result is not None- assert result.team_ids == []--[email protected](enablement, "is_dev_mode", return_value=False)[email protected](enablement.posthoganalytics, "feature_enabled")-def test_duckgres_sink_enablement_uses_memberships_and_carries_org_budgets(- mock_feature_enabled: MagicMock, _mock_dev: MagicMock-) -> None:- """The per-org sink_max_concurrency must ride along with each enabled team,- or the claim query silently applies no cap (empty mapping = uncapped)."""- org_a = Organization.objects.create(name="A")- org_b = Organization.objects.create(name="B")- team_a = Team.objects.create(organization=org_a)- team_b = Team.objects.create(organization=org_b)- Team.objects.create(organization=org_a)- mock_feature_enabled.return_value = True-- # Disabled events backfill does not revoke sink membership; the unregistered third- # team is never evaluated even though its org is provisioned.- with (- _patch_all_rows([_cp_row(team_a), _cp_row(team_b, backfill_enabled=False)]),- _patch_budgets({str(org_a.id): 4, str(org_b.id): 7}),- ):- result = enablement.duckgres_sink_enablement()-- assert result is not None- assert sorted(result.team_ids) == sorted([team_a.id, team_b.id])- assert set(result.team_org_budgets) == {- (team_a.id, str(org_a.id), 4), # model default- (team_b.id, str(org_b.id), 7),- }- assert mock_feature_enabled.call_count == 2--[email protected](enablement, "is_dev_mode", return_value=False)[email protected](enablement.posthoganalytics, "feature_enabled")-def test_duckgres_sink_enablement_ignores_non_uuid_control_plane_org_ids(- mock_feature_enabled: MagicMock, _mock_dev: MagicMock-) -> None:- """The control plane can report extra rows for a team keyed by a non-UUID- organization_id (e.g. dev/test rows using human-readable slugs instead of a real- org id). Those must not crash the whole refresh via a Django UUID lookup — they- should just fail the org match-up and be skipped, like any other mismatched row."""- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- mock_feature_enabled.return_value = True-- mismatched_row = replace(_cp_row(team), organization_id="not-a-uuid-slug")-- with _patch_all_rows([_cp_row(team), mismatched_row]), _patch_budgets({str(org.id): 4}):- result = enablement.duckgres_sink_enablement()-- assert result is not None- assert result.team_ids == [team.id]- mock_feature_enabled.assert_called_once()--[email protected](enablement, "is_dev_mode", return_value=False)[email protected](enablement.posthoganalytics, "feature_enabled")-def test_duckgres_sink_enablement_raises_when_control_plane_unreachable(- mock_feature_enabled: MagicMock, _mock_dev: MagicMock-) -> None:- # The consumer keeps its previous cached enablement on a raise; returning an empty- # enablement instead would silently stop the sink fleet-wide on a CP blip.- with _patch_all_rows(None):- with pytest.raises(RuntimeError):- enablement.duckgres_sink_enablement()-- mock_feature_enabled.assert_not_called()---def test_is_duckgres_sink_team_member_reads_the_control_plane() -> None:- org = Organization.objects.create(name="Org")- member = Team.objects.create(organization=org)- non_member = Team.objects.create(organization=org)-- with patch.object(enablement, "list_org_team_memberships", return_value=[_cp_row(member)]):- assert is_duckgres_sink_team_member(member.id) is True- assert is_duckgres_sink_team_member(non_member.id) is False-- with patch.object(enablement, "list_org_team_memberships", return_value=None):- with pytest.raises(RuntimeError):- is_duckgres_sink_team_member(member.id)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.pydeleted file mode 100644index 3a8eeee95b23..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py+++ /dev/null@@ -1,1255 +0,0 @@-from typing import Any--import pytest--import psycopg--from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (- _has_inflight_replace_run,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (- KIND_RETIRED_BY_REPLAN,- REASON_RETIRED_BY_REPLAN,- retire_backfill_run,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (- DUCKGRES_APPLY_TABLE,- DUCKGRES_LEASE_TABLE,- DUCKGRES_STATUS_TABLE,- DUCKGRES_STATUS_VIEW,- DuckgresBatchQueue,- _eligibility_ctes,- _team_scope,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- BATCH_TABLE,- LEASE_TABLE,- STATUS_TABLE,- STATUS_VIEW,- BatchQueue,-)---def _get_test_database_url() -> str:- from django.db import connection-- settings = connection.settings_dict- host = settings.get("HOST", "localhost") or "localhost"- port = settings.get("PORT", "5432") or "5432"- return f"postgres://{settings['USER']}:{settings['PASSWORD']}@{host}:{port}/{settings['NAME']}"---def _ensure_tables(conn: psycopg.Connection[Any]) -> None:- conn.execute(f"""- CREATE TABLE IF NOT EXISTS {BATCH_TABLE} (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- team_id BIGINT NOT NULL,- schema_id VARCHAR(200) NOT NULL,- source_id VARCHAR(200) NOT NULL,- job_id VARCHAR(200) NOT NULL,- run_uuid VARCHAR(200) NOT NULL,- batch_index INT NOT NULL,- s3_path TEXT NOT NULL,- row_count INT NOT NULL,- byte_size BIGINT NOT NULL,- is_final_batch BOOLEAN NOT NULL,- total_batches INT,- total_rows BIGINT,- sync_type VARCHAR(32) NOT NULL,- cumulative_row_count BIGINT NOT NULL DEFAULT 0,- resource_name VARCHAR(400) NOT NULL,- is_resume BOOLEAN NOT NULL DEFAULT FALSE,- is_first_ever_sync BOOLEAN NOT NULL DEFAULT FALSE,- metadata JSONB NOT NULL DEFAULT '{{}}'::jsonb,- latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',- latest_attempt SMALLINT NOT NULL DEFAULT 0,- state_changed_at TIMESTAMPTZ,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()- )- """)- # Self-heal pre-existing test DBs where CREATE TABLE IF NOT EXISTS is a no-op.- conn.execute(f"""- ALTER TABLE {BATCH_TABLE}- ADD COLUMN IF NOT EXISTS latest_state VARCHAR(32) NOT NULL DEFAULT 'pending',- ADD COLUMN IF NOT EXISTS latest_attempt SMALLINT NOT NULL DEFAULT 0,- ADD COLUMN IF NOT EXISTS state_changed_at TIMESTAMPTZ- """)- conn.execute(f"""- CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,- job_state VARCHAR(32) NOT NULL,- attempt SMALLINT NOT NULL DEFAULT 0,- exec_time TIMESTAMPTZ,- error_response JSONB,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()- )- """)- conn.execute(f"""- CREATE TABLE IF NOT EXISTS {DUCKGRES_STATUS_TABLE} (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,- job_state VARCHAR(32) NOT NULL,- attempt SMALLINT NOT NULL DEFAULT 0,- exec_time TIMESTAMPTZ,- error_response JSONB,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()- )- """)- conn.execute(f"""- CREATE TABLE IF NOT EXISTS {DUCKGRES_APPLY_TABLE} (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- team_id BIGINT NOT NULL,- schema_id VARCHAR(200) NOT NULL,- run_uuid VARCHAR(200) NOT NULL,- batch_index INT NOT NULL,- batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,- row_count INT NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- CONSTRAINT sbdga_unique_batch_apply UNIQUE (team_id, schema_id, run_uuid, batch_index)- )- """)- conn.execute(f"DROP VIEW IF EXISTS {STATUS_VIEW}")- conn.execute(f"""- CREATE VIEW {STATUS_VIEW} AS- SELECT DISTINCT ON (batch_id) *- FROM {STATUS_TABLE}- ORDER BY batch_id ASC, created_at DESC, id DESC- """)- conn.execute(f"DROP VIEW IF EXISTS {DUCKGRES_STATUS_VIEW}")- conn.execute(f"""- CREATE VIEW {DUCKGRES_STATUS_VIEW} AS- SELECT DISTINCT ON (batch_id) *- FROM {DUCKGRES_STATUS_TABLE}- ORDER BY batch_id ASC, created_at DESC, id DESC- """)- # Needed so the Delta queue's claim CTE (referenced by the contract test below) can plan.- conn.execute(f"""- CREATE TABLE IF NOT EXISTS {LEASE_TABLE} (- id BIGSERIAL PRIMARY KEY,- team_id BIGINT NOT NULL,- schema_id VARCHAR(200) NOT NULL,- owner_token VARCHAR(64) NOT NULL,- expires_at TIMESTAMPTZ NOT NULL,- acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),- CONSTRAINT sgl_team_schema_uniq UNIQUE (team_id, schema_id)- )- """)- conn.execute(f"""- CREATE TABLE IF NOT EXISTS {DUCKGRES_LEASE_TABLE} (- id BIGSERIAL PRIMARY KEY,- team_id BIGINT NOT NULL,- schema_id VARCHAR(200) NOT NULL,- owner_token VARCHAR(64) NOT NULL,- expires_at TIMESTAMPTZ NOT NULL,- acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),- CONSTRAINT sdgl_team_schema_uniq UNIQUE (team_id, schema_id)- )- """)---def _truncate_tables(conn: psycopg.Connection[Any]) -> None:- conn.execute(- f"TRUNCATE {DUCKGRES_APPLY_TABLE}, {DUCKGRES_STATUS_TABLE}, {STATUS_TABLE}, {BATCH_TABLE}, {LEASE_TABLE}, {DUCKGRES_LEASE_TABLE} RESTART IDENTITY CASCADE"- )---_BATCH_DEFAULTS: dict[str, Any] = {- "team_id": 1,- "schema_id": "schema-1",- "source_id": "source-1",- "job_id": "job-1",- "run_uuid": "run-1",- "batch_index": 0,- "s3_path": "s3://bucket/path",- "row_count": 100,- "byte_size": 1024,- "is_final_batch": False,- "total_batches": None,- "total_rows": None,- "sync_type": "full_refresh",- "cumulative_row_count": 0,- "resource_name": "test_resource",- "is_resume": False,- "is_first_ever_sync": False,- "metadata": {},-}---async def _insert_batch(conn: psycopg.AsyncConnection[Any], **overrides: Any) -> str:- return await BatchQueue.insert(conn, **{**_BATCH_DEFAULTS, **overrides})--[email protected](scope="session")-def _db_url() -> str:- return _get_test_database_url()--[email protected](scope="session", autouse=True)-def _create_tables(_db_url: str) -> None:- with psycopg.Connection.connect(_db_url, autocommit=True) as conn:- _ensure_tables(conn)--[email protected](autouse=True)-def _clean_tables(_db_url: str) -> None:- with psycopg.Connection.connect(_db_url, autocommit=True) as conn:- _truncate_tables(conn)- conn.execute("SELECT pg_advisory_unlock_all()")---async def conn(_db_url: str):- async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as c:- yield c--[email protected]_db(transaction=True)-class TestDuckgresBatchQueueEligibility:- @pytest.mark.asyncio- async def test_failed_delta_replace_run_is_not_inflight(- self, conn: psycopg.AsyncConnection[Any], _db_url: str- ) -> None:- run_uuid = "failed-replace-run"- head_id = await _insert_batch(- conn,- run_uuid=run_uuid,- batch_index=0,- sync_type="full_refresh",- is_final_batch=False,- is_resume=False,- )- await BatchQueue.update_status(conn, batch_id=head_id, job_state="succeeded", attempt=1)-- tail_id = await _insert_batch(conn, run_uuid=run_uuid, batch_index=1)- await BatchQueue.update_status(conn, batch_id=tail_id, job_state="failed", attempt=1)-- with psycopg.Connection.connect(_db_url, autocommit=True) as sync_conn:- assert not _has_inflight_replace_run(sync_conn, team_id=1, schema_id="schema-1")-- @pytest.mark.asyncio- async def test_ignores_batches_until_delta_succeeds(self, conn):- await _insert_batch(conn)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert batches == []-- @pytest.mark.asyncio- async def test_returns_delta_succeeded_batches(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert len(batches) == 1- assert str(batches[0].id) == batch_id-- @pytest.mark.asyncio- async def test_skips_duckgres_succeeded_batches(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert batches == []-- @pytest.mark.asyncio- async def test_returns_duckgres_retry_batches(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="waiting_retry", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert len(batches) == 1- assert batches[0].latest_attempt == 1-- @pytest.mark.asyncio- async def test_co_claims_consecutive_live_prefix_in_one_fetch(self, conn):- # A live run's delta-succeeded prefix drains in ONE claim (the chunk- # co-claim semantics): each fetch-rotation wait amortizes across the- # prefix instead of gating every batch — the head-of-line throughput- # ceiling behind the 2026-07 team-2 workflow_histories backlog.- first_id = await _insert_batch(conn, batch_index=0)- second_id = await _insert_batch(conn, batch_index=1)- await BatchQueue.update_status(conn, batch_id=first_id, job_state="succeeded", attempt=1)- await BatchQueue.update_status(conn, batch_id=second_id, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert [batch.batch_index for batch in batches] == [0, 1]-- @pytest.mark.asyncio- async def test_live_prefix_stops_at_a_non_delta_succeeded_gap(self, conn):- # Only the CONSECUTIVE delta-succeeded prefix is claimable: a gap fails- # closed exactly like the chunk gate, so ordering can never skip a hole.- first_id = await _insert_batch(conn, batch_index=0)- await _insert_batch(conn, batch_index=1)- third_id = await _insert_batch(conn, batch_index=2)- await BatchQueue.update_status(conn, batch_id=first_id, job_state="succeeded", attempt=1)- await BatchQueue.update_status(conn, batch_id=third_id, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert [batch.batch_index for batch in batches] == [0]-- @pytest.mark.asyncio- async def test_live_batch_blocked_behind_executing_predecessor(self, conn):- first_id = await _insert_batch(conn, batch_index=0)- second_id = await _insert_batch(conn, batch_index=1)- await BatchQueue.update_status(conn, batch_id=first_id, job_state="succeeded", attempt=1)- await BatchQueue.update_status(conn, batch_id=second_id, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.update_status(conn, batch_id=first_id, job_state="executing", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert batches == []-- @pytest.mark.asyncio- @pytest.mark.parametrize(- "backoff_seconds,expected_indexes",- [- (3600, []), # predecessor inside its backoff window gates the run- (0, [0, 1]), # backoff elapsed: predecessor and successor co-claim- ],- )- async def test_retry_backoff_gates_successor_live_batches(self, conn, backoff_seconds, expected_indexes):- first_id = await _insert_batch(conn, batch_index=0)- second_id = await _insert_batch(conn, batch_index=1)- await BatchQueue.update_status(conn, batch_id=first_id, job_state="succeeded", attempt=1)- await BatchQueue.update_status(conn, batch_id=second_id, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.update_status(conn, batch_id=first_id, job_state="waiting_retry", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", retry_backoff_base_seconds=backoff_seconds- )-- assert [b.batch_index for b in batches] == expected_indexes-- @pytest.mark.asyncio- async def test_final_marker_waits_for_matching_data_batch_apply(self, conn):- data_id = await _insert_batch(conn, batch_index=0, is_final_batch=False)- final_id = await _insert_batch(conn, batch_index=0, is_final_batch=True, total_batches=1, total_rows=100)- await BatchQueue.update_status(conn, batch_id=data_id, job_state="succeeded", attempt=1)- await BatchQueue.update_status(conn, batch_id=final_id, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- # Co-claimed in one fetch, data batch strictly first — the group loop- # applies in order and halts before the final on any non-success.- assert [str(batch.id) for batch in batches] == [data_id, final_id]-- @pytest.mark.asyncio- async def test_delta_failed_run_is_skipped(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- failed_id = await _insert_batch(conn, batch_index=1)- await BatchQueue.update_status(conn, batch_id=failed_id, job_state="failed", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert batches == []-- @pytest.mark.asyncio- async def test_duckgres_failed_run_is_skipped(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- failed_id = await _insert_batch(conn, batch_index=1)- await BatchQueue.update_status(conn, batch_id=failed_id, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.update_status(conn, batch_id=failed_id, job_state="failed", attempt=3)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert batches == []---async def _mark_applied_raw(- conn: psycopg.AsyncConnection[Any],- *,- batch_id: str,- run_uuid: str,- batch_index: int,- team_id: int = 1,- schema_id: str = "schema-1",-) -> None:- await conn.execute(- f"""- INSERT INTO {DUCKGRES_APPLY_TABLE} (team_id, schema_id, run_uuid, batch_index, batch_id, row_count)- VALUES (%s, %s, %s, %s, %s, 0)- """,- [team_id, schema_id, run_uuid, batch_index, batch_id],- )--[email protected]_db(transaction=True)-class TestDuckgresCrossRunOrdering:- @pytest.mark.asyncio- async def test_newer_run_blocked_while_older_run_incomplete(self, conn):- # run-1: batch 0 applied, batch 1 delta-succeeded but unapplied -> incomplete- old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)- old1 = await _insert_batch(conn, run_uuid="run-1", batch_index=1)- await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)- await BatchQueue.update_status(conn, batch_id=old1, job_state="succeeded", attempt=1)- await _mark_applied_raw(conn, batch_id=old0, run_uuid="run-1", batch_index=0)-- # run-2 (newer, same schema): batch 0 delta-succeeded- new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0)- await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- # Only the older run's next batch is eligible; run-2 waits behind it.- assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-1", 1)]-- @pytest.mark.asyncio- async def test_newer_run_eligible_once_older_run_failed(self, conn):- old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)- await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.update_status(conn, batch_id=old0, job_state="failed", attempt=3)-- new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0)- await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-2", 0)]-- @pytest.mark.asyncio- async def test_supersede_retires_older_run_when_replace_head_pending(self, conn):- # run-1: batch 0 applied, batch 1 delta-succeeded but unapplied- old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)- old1 = await _insert_batch(conn, run_uuid="run-1", batch_index=1)- await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)- await BatchQueue.update_status(conn, batch_id=old1, job_state="succeeded", attempt=1)- await _mark_applied_raw(conn, batch_id=old0, run_uuid="run-1", batch_index=0)-- # run-2: a full_refresh replace head (batch 0) is delta-succeeded- new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0, sync_type="full_refresh")- await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)-- superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn)- assert superseded == 1 # run-1's pending batch 1-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-2", 0)]-- @pytest.mark.asyncio- async def test_supersede_does_not_touch_incremental_successor(self, conn):- old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)- await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)-- # Newer incremental (not first-ever) run does not replace the table, so the- # older run's work must still apply first.- new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0, sync_type="incremental")- await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)-- superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn)- assert superseded == 0-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-1", 0)]--[email protected]_db(transaction=True)-class TestDuckgresTeamFilterAndBacklog:- @pytest.mark.asyncio- async def test_team_filter(self, conn):- batch_id = await _insert_batch(conn, team_id=1)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- # The same owner re-claims its own lease, so repeated fetches are fine.- assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", team_ids=[2]) == []- assert (- len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", team_ids=[1, 2]))- == 1- )- assert (- len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", team_ids=None)) == 1- )-- @pytest.mark.asyncio- async def test_backlog_stats(self, conn):- batch_id = await _insert_batch(conn, sync_type="incremental")- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- 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.- 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.- stats = await DuckgresBatchQueue.get_backlog_stats(- conn, blocked_schema_ids=["schema-1"], failing_schema_ids=["schema-1"]- )- 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.- 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.- 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)- 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):- """Eligibility now reads the denormalized ``latest_state`` column instead- of a per-row LATERAL join to the delta status table. Pin the exact case- that denormalization must still get right: a batch with a multi-row- status history (e.g. executing -> succeeded) is eligible because its- LATEST row is 'succeeded', while a batch stuck on its first ('executing')- row is not — the same answer the old latest-status LATERAL gave."""- multi_history_id = await _insert_batch(conn, run_uuid="run-latest-succeeded", batch_index=0)- await BatchQueue.update_status(conn, batch_id=multi_history_id, job_state="executing", attempt=1)- await BatchQueue.update_status(conn, batch_id=multi_history_id, job_state="succeeded", attempt=1)-- 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)-- 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:- """The team filter must become a plain, sargable ``= ANY(...)`` when- team_ids is a concrete (prod) list, and disappear entirely when unscoped- (dev/tests) — never the old ``%(team_ids)s IS NULL OR ...`` form, which- defeats index pruning under a bound parameter. See _team_scope's- docstring in jobs_db.py."""-- def test_team_scope_scoped_emits_plain_any(self) -> None:- assert _team_scope("cb", scoped=True) == "AND cb.team_id = ANY(%(team_ids)s)"-- def test_team_scope_unscoped_is_empty(self) -> None:- assert _team_scope("cb", scoped=False) == ""-- def test_eligibility_ctes_scoped_has_no_is_null_or(self) -> None:- # Other IS NULL OR predicates (e.g. the duckgres-status join) are- # unrelated and must stay; only the old non-sargable team_ids form- # must be gone.- assert "team_ids)s::bigint[] IS NULL OR" not in _eligibility_ctes(True)-- def test_eligibility_ctes_unscoped_has_no_team_ids_param(self) -> None:- assert "%(team_ids)s" not in _eligibility_ctes(False)-- def test_eligibility_ctes_scoped_uses_sargable_any(self) -> None:- assert "team_id = ANY(%(team_ids)s)" in _eligibility_ctes(True)-- @pytest.mark.django_db(transaction=True)- @pytest.mark.asyncio- async def test_backlog_stats_team_scoping_preserves_semantics(self, conn: psycopg.AsyncConnection[Any]) -> None:- """The sargable rewrite must count exactly the same batches as the old- ``IS NULL OR`` form: scoped to [1] counts only team 1's batch, and- unscoped (None) counts every team's batch."""- team1_batch = await _insert_batch(conn, team_id=1, run_uuid="run-team-1", schema_id="schema-1")- await BatchQueue.update_status(conn, batch_id=team1_batch, job_state="succeeded", attempt=1)-- 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)-- 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--[email protected]_db(transaction=True)-class TestBackfillGating:- @pytest.mark.asyncio- async def test_blocked_schema_live_batches_are_excluded(self, conn):- batch_id = await _insert_batch(conn, sync_type="incremental")- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- assert (- await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]- )- == []- )- assert (- len(- await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", blocked_schema_ids=["other"]- )- )- == 1- )-- @pytest.mark.asyncio- async def test_backfill_batches_pass_the_block(self, conn):- batch_id = await _insert_batch(- conn,- run_uuid="duckgres-backfill-schema-1-v7",- job_id="duckgres-backfill",- is_resume=True,- metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},- )- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]- )-- assert [b.run_uuid for b in batches] == ["duckgres-backfill-schema-1-v7"]-- @pytest.mark.asyncio- async def test_backfill_run_never_plans_as_replace_head(self, conn):- # is_resume=True keeps the synthetic full_refresh run out of supersede's- # replace-head set: a backfill must never retire other runs.- batch_id = await _insert_batch(- conn,- run_uuid="duckgres-backfill-schema-1-v7",- job_id="duckgres-backfill",- is_resume=True,- metadata={"duckgres_backfill": True},- )- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- old = await _insert_batch(conn, run_uuid="run-0", sync_type="incremental")- await BatchQueue.update_status(conn, batch_id=old, job_state="succeeded", attempt=1)-- assert await DuckgresBatchQueue.supersede_replaced_runs(conn) == 0--[email protected]_db(transaction=True)-class TestBackfillQueueContracts:- @pytest.mark.asyncio- async def test_pre_succeeded_synthetic_rows_invisible_to_delta_fetch(self, conn):- """The load-bearing trick: backfill rows must never be claimed by the- Delta consumer (it would load them into the Delta table) while being- immediately eligible for the duckgres fetch."""- batch_id = await _insert_batch(- conn,- run_uuid="duckgres-backfill-schema-1-v1-gdeadbeef",- job_id="duckgres-backfill",- is_resume=True,- metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},- )- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- assert await BatchQueue.get_unprocessed_and_lock(conn, owner_token="test-owner") == []-- duck = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert [str(b.id) for b in duck] == [batch_id]-- @pytest.mark.asyncio- async def test_backfill_chunks_ignore_older_live_runs(self, conn):- """The cross-run gate exempts backfill chunks from waiting on live- runs: pre-snapshot runs are retired separately, and post-snapshot- runs must apply AFTER the swap — neither may deadlock the backfill."""- live = await _insert_batch(conn, run_uuid="run-old", sync_type="incremental")- await BatchQueue.update_status(conn, batch_id=live, job_state="succeeded", attempt=1)-- chunk = await _insert_batch(- conn,- run_uuid="duckgres-backfill-schema-1-v1-gcafe0000",- job_id="duckgres-backfill",- is_resume=True,- metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},- )- await BatchQueue.update_status(conn, batch_id=chunk, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]- )- assert [str(b.id) for b in batches] == [chunk]-- @pytest.mark.asyncio- async def test_live_batches_still_queue_behind_backfill_run(self, conn):- chunk = await _insert_batch(- conn,- run_uuid="duckgres-backfill-schema-1-v1-gcafe0000",- job_id="duckgres-backfill",- is_resume=True,- metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},- )- await BatchQueue.update_status(conn, batch_id=chunk, job_state="succeeded", attempt=1)-- live = await _insert_batch(conn, run_uuid="run-new")- await BatchQueue.update_status(conn, batch_id=live, job_state="succeeded", attempt=1)-- # Schema primed (not blocked) but the backfill run is older and- # incomplete: the live batch must wait.- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert [str(b.id) for b in batches] == [chunk]-- @pytest.mark.asyncio- async def test_preapply_covered_batches_uses_snapshot_commit_keys(self, conn, _db_url):- """Batches committed into the pinned Delta snapshot get pre-applied- regardless of queue timing; siblings absent from the snapshot key set- survive, stay eligible, and their run is never poisoned."""- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import (- backfill_queue,- )-- covered_a = await _insert_batch(conn, run_uuid="run-straddling", batch_index=0)- await BatchQueue.update_status(conn, batch_id=covered_a, job_state="succeeded", attempt=1)- late_b = await _insert_batch(conn, run_uuid="run-straddling", batch_index=1)- await BatchQueue.update_status(conn, batch_id=late_b, job_state="succeeded", attempt=1)-- with psycopg.Connection.connect(_db_url, autocommit=True) as sync_conn:- preapplied = backfill_queue.preapply_covered_batches(- sync_conn,- team_id=1,- schema_id="schema-1",- covered_batches=[("run-straddling", 0)],- reason="covered v1",- )- preapplied_again = backfill_queue.preapply_covered_batches(- sync_conn,- team_id=1,- schema_id="schema-1",- covered_batches=[("run-straddling", 0)],- reason="covered v1",- )-- assert preapplied == 1 # covered_a only- assert preapplied_again == 0 # idempotent; late_b is absent from the snapshot key set-- # The straddling sibling is NOT lost: its head-of-line prev is satisfied- # by the pre-apply marker, the run is not failed, and it remains the- # schema's claimable work (post-swap it applies as a live batch).- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert [str(b.id) for b in batches] == [late_b]-- @pytest.mark.asyncio- async def test_replace_head_runs_bypass_the_blocked_gate(self, conn):- """A full-refresh replace run rebuilds the table from scratch, so it is- safe (and required — it is the NEEDS_RESYNC healing path) even while- the schema is not primed. Non-head live runs stay blocked."""- plain = await _insert_batch(conn, run_uuid="run-plain", sync_type="incremental")- await BatchQueue.update_status(conn, batch_id=plain, job_state="succeeded", attempt=1)-- head = await _insert_batch(conn, run_uuid="run-refresh", sync_type="full_refresh", batch_index=0)- await BatchQueue.update_status(conn, batch_id=head, job_state="succeeded", attempt=1)-- # Retire the plain run first so the cross-run gate isn't what hides it.- await DuckgresBatchQueue.update_status(conn, batch_id=plain, job_state="failed", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]- )- assert [str(b.id) for b in batches] == [head]-- @pytest.mark.asyncio- async def test_eligible_schema_ids_restricts_claim_to_v3_schemas(self, conn):- # The v3 allow-list must exclude a claimable (delta-succeeded, unblocked)- # batch when its schema is not v3-enabled — the default batch is- # full_refresh, which otherwise bypasses the unprimed block. Guards the- # leak where non-v3 (e.g. Postgres) batches were applied via the- # team-scoped claim. None = no filter (dev/tests); [] = nothing eligible.- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- async def claim(eligible: list[str] | None) -> list[Any]:- return await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", eligible_schema_ids=eligible- )-- assert len(await claim(None)) == 1- assert len(await claim(["schema-1"])) == 1- assert await claim(["other-schema"]) == []- assert await claim([]) == []-- @pytest.mark.asyncio- async def test_eligible_gate_excludes_replace_head_that_bypasses_block(self, conn):- # A full_refresh replace-head bypasses the unprimed block, but the v3- # allow-list must still exclude it when the schema is not v3-enabled — the- # eligibility gate overrides the replace-head carve-out.- head = await _insert_batch(conn, run_uuid="run-refresh", sync_type="full_refresh", batch_index=0)- await BatchQueue.update_status(conn, batch_id=head, job_state="succeeded", attempt=1)-- bypasses = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", blocked_schema_ids=["schema-1"]- )- assert [str(b.id) for b in bypasses] == [head]-- gated = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", blocked_schema_ids=["schema-1"], eligible_schema_ids=["other-schema"]- )- assert gated == []---async def _insert_chunk(- conn: psycopg.AsyncConnection[Any],- *,- batch_index: int,- chunk_count: int = 3,- run_uuid: str = "duckgres-backfill-schema-1-v1-g00000000",- delta_succeeded: bool = True,-) -> str:- batch_id = await _insert_batch(- conn,- run_uuid=run_uuid,- job_id="duckgres-backfill",- is_resume=True,- batch_index=batch_index,- metadata={- "duckgres_backfill": True,- "chunk_paths": [f"s3://b/c{batch_index}.parquet"],- "chunk_count": chunk_count,- },- )- if delta_succeeded:- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- return batch_id--[email protected]_db(transaction=True)-class TestBackfillChunkClaiming:- @pytest.mark.asyncio- async def test_whole_backfill_run_claimable_in_one_fetch(self, conn):- for i in range(3):- await _insert_chunk(conn, batch_index=i)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- # Chunks must come back in index order: the group loop applies them- # sequentially, so chunk 0's CREATE always lands before the inserts.- assert [b.batch_index for b in batches] == [0, 1, 2]-- @pytest.mark.asyncio- async def test_chunks_blocked_behind_executing_predecessor(self, conn):- chunk0 = await _insert_chunk(conn, batch_index=0)- await _insert_chunk(conn, batch_index=1)- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="executing", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert batches == []-- @pytest.mark.asyncio- async def test_replayed_predecessor_with_newer_created_at_blocks_successor(self, conn):- # A reconcile replay re-inserts chunk 0 with a fresh created_at, so it- # sorts AFTER chunk 1; chunk 1 must stay blocked until chunk 0 applies- # (co-claiming it would apply before the CREATE — data loss).- await _insert_chunk(conn, batch_index=1, chunk_count=2)- chunk0 = await _insert_chunk(conn, batch_index=0, chunk_count=2)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert [b.batch_index for b in batches] == [0]-- await _mark_applied_raw(- conn, batch_id=chunk0, run_uuid="duckgres-backfill-schema-1-v1-g00000000", batch_index=0- )- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches, owner_token="owner-a")-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert [b.batch_index for b in batches] == [1]-- @pytest.mark.asyncio- async def test_chunks_blocked_behind_non_delta_succeeded_predecessor(self, conn):- # enqueue_chunks writes chunks pre-succeeded atomically, so this state- # shouldn't exist — the gate must fail closed anyway.- await _insert_chunk(conn, batch_index=0, delta_succeeded=False)- await _insert_chunk(conn, batch_index=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert batches == []-- @pytest.mark.asyncio- @pytest.mark.parametrize(- "backoff_seconds,expected_indexes",- [- (3600, []), # predecessor inside its backoff window gates the run- (0, [0, 1]), # backoff elapsed: predecessor and successor co-claim- ],- )- async def test_retry_backoff_gates_successor_chunks(self, conn, backoff_seconds, expected_indexes):- chunk0 = await _insert_chunk(conn, batch_index=0, chunk_count=2)- await _insert_chunk(conn, batch_index=1, chunk_count=2)- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="waiting_retry", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", retry_backoff_base_seconds=backoff_seconds- )-- assert [b.batch_index for b in batches] == expected_indexes-- @pytest.mark.asyncio- async def test_executing_insert_refuses_when_latest_status_is_failed(self, conn):- # A supersede landing between the retire check and the executing write- # must block the insert, or the new row masks the terminal 'failed'.- chunk0 = await _insert_chunk(conn, batch_index=0)-- assert await DuckgresBatchQueue.update_status_unless_failed(conn, batch_id=chunk0, job_state="executing")- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="failed", attempt=0)-- assert not await DuckgresBatchQueue.update_status_unless_failed(conn, batch_id=chunk0, job_state="executing")- assert await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)-- # A reset-style revive (fresh non-failed status) reopens the path.- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="waiting_retry", attempt=1)- assert await DuckgresBatchQueue.update_status_unless_failed(conn, batch_id=chunk0, job_state="executing")-- @pytest.mark.asyncio- async def test_is_failed_tracks_latest_status(self, conn):- # The mid-claim retire check must see a 'failed' written under a- # claimed chunk, and a later status must clear it (latest-row wins).- chunk0 = await _insert_chunk(conn, batch_index=0)- assert not await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)-- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="failed", attempt=0)- assert await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)-- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="succeeded", attempt=1)- assert not await DuckgresBatchQueue.is_failed(conn, batch_id=chunk0)-- @pytest.mark.asyncio- async def test_applied_predecessor_does_not_block(self, conn):- chunk0 = await _insert_chunk(conn, batch_index=0)- await _insert_chunk(conn, batch_index=1)- await _mark_applied_raw(- conn, batch_id=chunk0, run_uuid="duckgres-backfill-schema-1-v1-g00000000", batch_index=0- )- await DuckgresBatchQueue.update_status(conn, batch_id=chunk0, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")-- assert [b.batch_index for b in batches] == [1]--[email protected]_db(transaction=True)-class TestDuckgresGroupLease:- @pytest.mark.asyncio- async def test_live_lease_blocks_other_owner_until_released(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)-- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- assert len(claimed) == 1-- assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b") == []-- # A non-owner's unlock must not release owner-a's lease.- await DuckgresBatchQueue.unlock_for_batches(conn, batches=claimed, owner_token="owner-b")- assert await DuckgresBatchQueue.verify_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")-- await DuckgresBatchQueue.unlock_for_batches(conn, batches=claimed, owner_token="owner-a")- assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b")) == 1-- @pytest.mark.asyncio- async def test_max_groups_caps_leased_groups_leaving_the_rest_claimable(self, conn):- # A pod must not lease groups it has no slot to start — every poll- # renews them, blocking other pods.- older = await _insert_batch(conn, schema_id="schema-1")- await BatchQueue.update_status(conn, batch_id=older, job_state="succeeded", attempt=1)- newer = await _insert_batch(conn, schema_id="schema-2")- await BatchQueue.update_status(conn, batch_id=newer, job_state="succeeded", attempt=1)-- capped = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", max_groups=1)- assert [str(b.id) for b in capped] == [older]-- # The uncapped group carries no lease, so another owner claims it now.- other = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b", max_groups=1)- assert [str(b.id) for b in other] == [newer]-- @pytest.mark.asyncio- async def test_excluded_in_flight_groups_do_not_consume_the_claim_budget(self, conn):- # Re-claiming an in-flight group burns the max_groups budget and- # starves other schemas.- mine = await _insert_batch(conn, schema_id="schema-1")- await BatchQueue.update_status(conn, batch_id=mine, job_state="succeeded", attempt=1)- other = await _insert_batch(conn, schema_id="schema-2")- await BatchQueue.update_status(conn, batch_id=other, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", max_groups=1, exclude_groups=[(1, "schema-1")]- )-- assert [str(b.id) for b in batches] == [other]-- @pytest.mark.asyncio- async def test_other_owners_leased_group_cannot_flood_the_candidate_limit(self, conn):- # Another pod's leased backfill must be filtered BEFORE the candidate- # LIMIT, or its chunks fill the window and hide other schemas' work.- for i in range(3):- await _insert_chunk(conn, batch_index=i)- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b")- assert len(claimed) == 3 # owner-b holds the group's lease; chunks stay statusless-- live = await _insert_batch(conn, schema_id="schema-2")- await BatchQueue.update_status(conn, batch_id=live, job_state="succeeded", attempt=1)-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a", limit=3)-- assert [str(b.id) for b in batches] == [live]-- @pytest.mark.asyncio- async def test_expired_lease_is_reclaimable_by_another_owner(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")-- # An expired lease is dead even for its original owner — the only way- # back in is the fetch's claim CTE.- assert not await DuckgresBatchQueue.renew_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")-- assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-b")) == 1- assert not await DuckgresBatchQueue.renew_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-a")- assert await DuckgresBatchQueue.renew_lease(conn, team_id=1, schema_id="schema-1", owner_token="owner-b")-- @pytest.mark.asyncio- async def test_requeue_is_fenced_on_live_lease_and_current_status(self, conn):- # The requeue write must re-check lease and status in its own snapshot,- # or the scan-to-write gap stamps waiting_retry into an owned group.- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=1)-- # Live lease (owner-a) → requeue and terminal failure must refuse.- assert not await DuckgresBatchQueue.requeue_stale_executing(- conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=0- )- assert not await DuckgresBatchQueue.fail_run_if_stale(- conn, batch=claimed[0], reason="timed out", grace_seconds=0- )- assert not await DuckgresBatchQueue.is_failed(conn, batch_id=batch_id)-- await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")- assert await DuckgresBatchQueue.requeue_stale_executing(- conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=0- )-- # Latest is now waiting_retry: a rival sweep's second requeue is a- # no-op, and the fenced terminal failure no longer fires either.- assert not await DuckgresBatchQueue.requeue_stale_executing(- conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=0- )- assert not await DuckgresBatchQueue.fail_run_if_stale(- conn, batch=claimed[0], reason="timed out", grace_seconds=0- )-- @pytest.mark.asyncio- async def test_fresh_executing_heartbeat_blocks_recovery_writes(self, conn):- # An old advisory-lock pod processes leaselessly, heartbeating fresh- # 'executing' rows; recovery writes must re-check the status AGE or- # they requeue/fail a batch that is demonstrably alive.- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=1)- await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")-- assert not await DuckgresBatchQueue.requeue_stale_executing(- conn, batch=claimed[0], error_response={"error": "timed out"}, grace_seconds=3600- )- assert not await DuckgresBatchQueue.fail_run_if_stale(- conn, batch=claimed[0], reason="max retries exceeded", grace_seconds=3600- )- assert not await DuckgresBatchQueue.is_failed(conn, batch_id=batch_id)-- @pytest.mark.asyncio- async def test_fenced_terminal_failure_fires_only_while_stale_and_unowned(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=3)- await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")-- assert await DuckgresBatchQueue.fail_run_if_stale(- conn, batch=claimed[0], reason="max retries exceeded", grace_seconds=0- )- assert await DuckgresBatchQueue.is_failed(conn, batch_id=batch_id)-- @pytest.mark.asyncio- async def test_stale_executing_visible_only_after_lease_expiry(self, conn):- batch_id = await _insert_batch(conn)- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, owner_token="owner-a")- await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="executing", attempt=1)-- assert await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=0) == []-- await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")- stale = await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=0)- assert [str(b.id) for b in stale] == [batch_id]--[email protected]_db(transaction=True)-class TestOrgConcurrencyBudget:- # (team_id, org_id, budget) rows: teams 1 and 2 belong to org-a, team 3 to org-b.- TWO_ORGS = [(1, "org-a", 2), (2, "org-a", 2), (3, "org-b", 4)]-- async def _eligible_group(self, conn, *, team_id: int, schema_id: str) -> str:- batch_id = await _insert_batch(conn, team_id=team_id, schema_id=schema_id, run_uuid=f"run-{schema_id}")- await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- return batch_id-- @pytest.mark.asyncio- async def test_budget_caps_groups_within_one_fetch(self, conn):- # A single poll must not lease an org's whole schema backlog at once —- # each leased group is a potential connection to the org's duckgres.- await self._eligible_group(conn, team_id=1, schema_id="s1")- await self._eligible_group(conn, team_id=1, schema_id="s2")- await self._eligible_group(conn, team_id=2, schema_id="s3")-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", team_org_budgets=self.TWO_ORGS- )-- # Oldest two groups win org-a's budget of 2; the third is left unleased.- assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s1"), (1, "s2")}-- @pytest.mark.asyncio- async def test_other_pods_live_leases_count_toward_budget_until_expiry(self, conn):- await self._eligible_group(conn, team_id=1, schema_id="s1")- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="other-pod", team_org_budgets=self.TWO_ORGS- )- assert len(claimed) == 1-- await self._eligible_group(conn, team_id=1, schema_id="s2")- await self._eligible_group(conn, team_id=2, schema_id="s3")-- # other-pod's live lease occupies 1 of org-a's 2 slots fleet-wide.- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", team_org_budgets=self.TWO_ORGS- )- assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s2")}-- # Expired leases return their slots: the two OLDEST org-a groups claim- # (s1's expired lease is reclaimable, s2 re-claims), and s3 - also- # org-a, via team 2 - is still budget-skipped as the third-ranked group.- await conn.execute(f"UPDATE {DUCKGRES_LEASE_TABLE} SET expires_at = now() - interval '1 second'")- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", team_org_budgets=self.TWO_ORGS- )- assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s1"), (1, "s2")}-- @pytest.mark.asyncio- async def test_saturated_org_does_not_block_other_orgs_groups(self, conn):- # Work-conservation: a capped org's OLDER work must be skipped, not- # deferred, or it head-of-line blocks the pod's max_groups budget.- one_slot = [(1, "org-a", 1), (3, "org-b", 4)]- await self._eligible_group(conn, team_id=1, schema_id="s1")- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="other-pod", team_org_budgets=one_slot- )- assert len(claimed) == 1 # org-a saturated-- await self._eligible_group(conn, team_id=1, schema_id="s2") # older than org-b's work- await self._eligible_group(conn, team_id=3, schema_id="s3")-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", max_groups=1, team_org_budgets=one_slot- )-- assert {(b.team_id, b.schema_id) for b in batches} == {(3, "s3")}-- @pytest.mark.asyncio- async def test_saturated_orgs_deep_backlog_cannot_fill_the_candidate_window(self, conn):- # The budget filter must apply BEFORE the candidate LIMIT, like the- # other-owner lease exclusion above it: a fully saturated org's deep- # backlog would otherwise fill the window with rows the group filter- # then drops, and the pod claims NOTHING while other orgs have work.- one_slot = [(1, "org-a", 1), (3, "org-b", 4)]- await self._eligible_group(conn, team_id=1, schema_id="s0")- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="other-pod", team_org_budgets=one_slot- )- assert len(claimed) == 1 # org-a saturated-- for i in range(3): # org-a backlog, all older than org-b's work- await self._eligible_group(conn, team_id=1, schema_id=f"s{i + 1}")- await self._eligible_group(conn, team_id=3, schema_id="sb")-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", limit=3, team_org_budgets=one_slot- )-- assert {(b.team_id, b.schema_id) for b in batches} == {(3, "sb")}-- @pytest.mark.asyncio- async def test_unmapped_team_is_uncapped(self, conn):- # The mapping caps; it must never act as an eligibility filter —- # team_ids/eligible_schema_ids own that. A team missing from the- # mapping (dev, or a mid-refresh race) claims freely.- await self._eligible_group(conn, team_id=1, schema_id="s1")- await self._eligible_group(conn, team_id=1, schema_id="s2")-- batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="owner-a", team_org_budgets=[(99, "org-x", 1)]- )-- assert {(b.team_id, b.schema_id) for b in batches} == {(1, "s1"), (1, "s2")}-- @pytest.mark.asyncio- async def test_count_orgs_at_budget(self, conn):- one_each = [(1, "org-a", 1), (3, "org-b", 2)]- await self._eligible_group(conn, team_id=1, schema_id="s1")- await self._eligible_group(conn, team_id=3, schema_id="s2")- claimed = await DuckgresBatchQueue.get_delta_succeeded_and_lock(- conn, owner_token="other-pod", team_org_budgets=one_each- )- assert len(claimed) == 2-- # org-a: 1 live lease of budget 1 -> saturated; org-b: 1 of 2 -> not.- assert await DuckgresBatchQueue.count_orgs_at_budget(conn, team_org_budgets=one_each) == 1--[email protected]_db(transaction=True)-class TestRetireBackfillRun:- @pytest.mark.asyncio- async def test_marks_unapplied_chunks_failed_with_replan_reason(- self, conn: psycopg.AsyncConnection[Any], _db_url: str- ) -> None:- # Regression: retire_backfill_run built error_response with bare- # placeholders inside jsonb_build_object (a VARIADIC "any" function), so- # Postgres raised IndeterminateDatatype ("could not determine data type- # of parameter $1") on EVERY replan of a schema that still had a live- # backfill_run_uuid -- silently blocking operator un-sticking. The- # ::text casts fix it; this test executes the real SQL that regressed.- run_uuid = "run-to-retire"- b0 = await _insert_batch(conn, run_uuid=run_uuid, batch_index=0)- b1 = await _insert_batch(conn, run_uuid=run_uuid, batch_index=1)- # An already-applied chunk must be left alone (the a.id IS NULL filter).- applied = await _insert_batch(conn, run_uuid=run_uuid, batch_index=2)- await _mark_applied_raw(conn, batch_id=applied, run_uuid=run_uuid, batch_index=2)-- # retire_backfill_run takes a *sync* psycopg connection (it runs inline- # in the consumer fetch path), so open one against the same test DB.- with psycopg.Connection.connect(_db_url, autocommit=True) as sync_conn:- retire_backfill_run(sync_conn, run_uuid=run_uuid)-- cur = await conn.execute(f"SELECT batch_id, job_state, error_response FROM {DUCKGRES_STATUS_TABLE}")- rows = await cur.fetchall()-- retired = {str(batch_id): (job_state, err) for batch_id, job_state, err in rows}- assert set(retired) == {str(b0), str(b1)} # applied chunk untouched- for job_state, err in retired.values():- assert job_state == "failed"- assert err["error"] == REASON_RETIRED_BY_REPLAN- assert err["kind"] == KIND_RETIRED_BY_REPLAN- assert await DuckgresBatchQueue.count_orgs_at_budget(conn, team_org_budgets=[]) == 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.pydeleted file mode 100644index ef1ed07e0e24..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py+++ /dev/null@@ -1,811 +0,0 @@-from typing import Any--import pytest-from unittest.mock import MagicMock, Mock, patch--import psycopg--from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor import (- DuckgresColumn,- _ensure_duckgres_apply_table,- _insert_batch,- _mark_duckgres_batch_applied,- _process_backfill_batch,- _process_batch,- _session_cache,- _table_exists,- process_batch,-)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- PendingBatch,-)--[email protected](autouse=True)-def _stub_schema_resolver():- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.duckgres_data_imports_schema",- return_value="posthog_data_imports_team_1",- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.duckgres_data_imports_table_name",- return_value="stripe_customers",- ),- ):- yield---def _make_batch(**overrides: Any) -> PendingBatch:- defaults: dict[str, Any] = {- "id": "00000000-0000-0000-0000-000000000001",- "team_id": 1,- "schema_id": "schema-1",- "source_id": "source-1",- "job_id": "job-1",- "run_uuid": "run-1",- "batch_index": 0,- "s3_path": "s3://bucket/path",- "row_count": 100,- "byte_size": 1024,- "is_final_batch": False,- "total_batches": None,- "total_rows": None,- "sync_type": "incremental",- "cumulative_row_count": 0,- "resource_name": "test_resource",- "is_resume": False,- "is_first_ever_sync": False,- "metadata": {},- "latest_attempt": 0,- }- defaults.update(overrides)- return PendingBatch(**defaults)---def _make_schema() -> Mock:- schema = Mock()- schema.team_id = 1- schema.normalized_name = "customers"- schema.source.source_type = "Stripe"- schema.source.prefix = None- return schema---def _make_conn() -> MagicMock:- return MagicMock()---def _parquet_schema() -> list[DuckgresColumn]:- return [DuckgresColumn("id", "BIGINT"), DuckgresColumn("email", "VARCHAR")]---class _RecordingTransaction:- def __init__(self, conn: "_RecordingConn") -> None:- self.conn = conn-- def __enter__(self) -> None:- self.conn.in_transaction = True- self.conn.events.append("transaction:start")-- def __exit__(self, *args: object) -> None:- self.conn.events.append("transaction:end")- self.conn.in_transaction = False---class _RecordingConn:- def __init__(self) -> None:- self.execute = MagicMock()- self.events: list[str] = []- self.in_transaction = False-- def transaction(self) -> _RecordingTransaction:- return _RecordingTransaction(self)---def test_first_ever_incremental_batch_replaces_table() -> None:- conn = _make_conn()- batch = _make_batch(batch_index=0, is_first_ever_sync=True, is_resume=False, sync_type="incremental")-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table"- ) as replace_table,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists"- ) as table_exists,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch"- ) as merge_batch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"- ) as insert_batch,- ):- _process_batch(conn, batch, _make_schema())-- replace_table.assert_called_once()- table_exists.assert_not_called()- merge_batch.assert_not_called()- insert_batch.assert_not_called()---def test_existing_incremental_batch_zero_merges_after_first_sync() -> None:- conn = _make_conn()- batch = _make_batch(- batch_index=0,- sync_type="incremental",- is_first_ever_sync=False,- metadata={"primary_keys": ["id"]},- )-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table"- ) as replace_table,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",- create=True,- ) as ensure_columns,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch"- ) as merge_batch,- ):- _process_batch(conn, batch, _make_schema())-- replace_table.assert_not_called()- ensure_columns.assert_called_once_with(conn, "posthog_data_imports_team_1", "stripe_customers", _parquet_schema())- merge_batch.assert_called_once()---def test_first_ever_incremental_followup_batch_inserts_without_primary_keys() -> None:- conn = _make_conn()- batch = _make_batch(- batch_index=1,- sync_type="incremental",- is_first_ever_sync=True,- metadata={},- )-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",- create=True,- ) as ensure_columns,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"- ) as insert_batch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch"- ) as merge_batch,- ):- _process_batch(conn, batch, _make_schema())-- ensure_columns.assert_called_once_with(conn, "posthog_data_imports_team_1", "stripe_customers", _parquet_schema())- insert_batch.assert_called_once()- merge_batch.assert_not_called()---def test_existing_incremental_table_merges_after_first_sync() -> None:- conn = _make_conn()- batch = _make_batch(- batch_index=1,- sync_type="incremental",- is_first_ever_sync=False,- metadata={"primary_keys": ["id"]},- )-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",- create=True,- ) as ensure_columns,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"- ) as insert_batch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch"- ) as merge_batch,- ):- _process_batch(conn, batch, _make_schema())-- ensure_columns.assert_called_once_with(conn, "posthog_data_imports_team_1", "stripe_customers", _parquet_schema())- insert_batch.assert_not_called()- merge_batch.assert_called_once()---def test_schema_evolution_merge_and_apply_marker_are_one_transaction() -> None:- conn: Any = _RecordingConn()- batch = _make_batch(- batch_index=1,- sync_type="incremental",- is_first_ever_sync=False,- metadata={"primary_keys": ["id"]},- )-- def ensure_columns(*args: object) -> None:- assert conn.in_transaction- conn.events.append("ensure_columns")-- def merge_batch(*args: object) -> None:- assert conn.in_transaction- conn.events.append("merge")-- def mark_applied(*args: object, **kwargs: object) -> None:- assert conn.in_transaction- conn.events.append("mark")-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",- side_effect=ensure_columns,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch",- side_effect=merge_batch,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied",- side_effect=mark_applied,- ),- ):- _process_batch(conn, batch, _make_schema())-- assert conn.events == ["transaction:start", "ensure_columns", "merge", "mark", "transaction:end"]---def test_missing_table_is_created_from_parquet() -> None:- conn = _make_conn()- batch = _make_batch(- batch_index=1,- sync_type="incremental",- is_first_ever_sync=False,- metadata={"primary_keys": ["id"]},- )-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._create_table_from_parquet"- ) as create_table,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch"- ) as merge_batch,- ):- _process_batch(conn, batch, _make_schema())-- create_table.assert_called_once()- merge_batch.assert_not_called()---def test_insert_batch_uses_explicit_column_projection() -> None:- conn = _make_conn()-- _insert_batch(conn, "warehouse", "customers", ["s3://bucket/path"], ["id", "email"])-- query = conn.execute.call_args.args[0]- assert "SELECT *" not in repr(query)- assert "s3://bucket/path" in repr(query) # path is inlined as a literal now---def test_already_applied_batch_skips_duckgres_mutation() -> None:- conn = _make_conn()- batch = _make_batch(batch_index=0, is_first_ever_sync=True)-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table",- create=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- create=True,- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ) as read_schema,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table"- ) as replace_table,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"- ) as insert_batch,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch"- ) as merge_batch,- ):- _process_batch(conn, batch, _make_schema())-- read_schema.assert_not_called()- replace_table.assert_not_called()- insert_batch.assert_not_called()- merge_batch.assert_not_called()---def test_marks_duckgres_batch_applied_after_successful_mutation() -> None:- conn = _make_conn()- batch = _make_batch(batch_index=0, is_first_ever_sync=True)-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table",- create=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- create=True,- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table"- ) as replace_table,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied",- create=True,- ) as mark_applied,- ):- _process_batch(conn, batch, _make_schema())-- replace_table.assert_called_once()- mark_applied.assert_called_once_with(conn, "posthog_data_imports_team_1", batch=batch)---def test_duckgres_apply_marker_is_scoped_by_schema_id() -> None:- conn = _make_conn()- batch = _make_batch(schema_id="schema-1", run_uuid="run-1", batch_index=2)-- _ensure_duckgres_apply_table(conn, "warehouse")- create_query = conn.execute.call_args.args[0]-- assert "schema_id" in repr(create_query)- assert "PRIMARY KEY (schema_id, run_uuid, batch_index)" in repr(create_query)-- _mark_duckgres_batch_applied(conn, "warehouse", batch=batch)-- query = conn.execute.call_args.args[0]- assert "ON CONFLICT (schema_id, run_uuid, batch_index)" in repr(query)- assert conn.execute.call_args.args[1] == [- "schema-1",- "run-1",- 2,- "00000000-0000-0000-0000-000000000001",- ]---def _make_backfill_batch(**overrides: Any) -> PendingBatch:- md = {- "duckgres_backfill": True,- "chunk_paths": ["s3://bucket/chunk_0.parquet"],- "chunk_count": 3,- }- md.update(overrides.pop("metadata", {}))- return _make_batch(- job_id="duckgres-backfill",- run_uuid="duckgres-backfill-schema-1-v7",- sync_type="full_refresh",- is_resume=True,- metadata=md,- **overrides,- )---class TestBackfillProcessing:- def test_first_chunk_creates_backfill_table_without_swap(self) -> None:- conn = _make_conn()- batch = _make_backfill_batch(batch_index=0)-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied"- ) as mark,- ):- _process_backfill_batch(conn, batch, _make_schema())-- executed = " ".join(repr(c.args[0]) for c in conn.execute.call_args_list)- assert "stripe_customers__bf_schema1" in executed- assert "CREATE OR REPLACE TABLE" in executed- assert "RENAME TO" not in executed- mark.assert_called_once()-- def test_last_chunk_swaps_and_marks_primed(self) -> None:- conn = _make_conn()- batch = _make_backfill_batch(batch_index=2, metadata={"chunk_paths": ["s3://bucket/chunk_2.parquet"]})-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=False,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",- return_value=_parquet_schema(),- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"- ) as insert,- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill.mark_primed"- ) as primed,- ):- _process_backfill_batch(conn, batch, _make_schema())-- executed = " ".join(repr(c.args[0]) for c in conn.execute.call_args_list)- assert "DROP TABLE IF EXISTS" in executed- assert "Identifier('stripe_customers')" in executed- assert "RENAME TO" in executed- insert.assert_called_once()- primed.assert_called_once_with("schema-1", run_uuid="duckgres-backfill-schema-1-v7", chunks_applied=3)-- def test_already_applied_chunk_is_a_noop(self) -> None:- conn = _make_conn()- batch = _make_backfill_batch(batch_index=1)-- with (- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",- return_value=True,- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"- ) as insert,- ):- _process_backfill_batch(conn, batch, _make_schema())-- insert.assert_not_called()---class TestLiveSessionReuse:- """Reusing the duckgres session across a group's live batches removes the- dominant per-batch fixed costs measured in prod on 2026-07-22: worker- session create, the describe probe's cold catalog enumeration, and the- first-write metadata touch (~20-40s combined per batch)."""-- @pytest.fixture(autouse=True)- def _reset_cache_and_orm(self):- _session_cache.clear()- patches = [- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.close_old_connections"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.ExternalDataJob"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.Team"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._process_batch"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.setup_duckgres_session"- ),- patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._create_extract_read_secret"- ),- ]- self.mocks = [p.start() for p in patches]- (_, self.mock_job, self.mock_team, self.mock_inner, self.mock_setup, self.mock_secret) = self.mocks- self.mock_team.objects.only.return_value.get.return_value.organization_id = "org-a"- yield- for p in patches:- p.stop()- _session_cache.clear()-- def _connect_patch(self):- return patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._connect_to_duckgres"- )-- def test_consecutive_live_batches_reuse_one_connection_and_preamble(self):- with self._connect_patch() as mock_connect:- mock_connect.return_value = MagicMock()- process_batch(_make_batch(batch_index=1))- process_batch(_make_batch(batch_index=2))-- assert mock_connect.call_count == 1- assert self.mock_setup.call_count == 1- assert self.mock_secret.call_count == 1- assert self.mock_inner.call_count == 2-- def test_groups_get_separate_connections(self):- with self._connect_patch() as mock_connect:- mock_connect.side_effect = [MagicMock(), MagicMock()]- process_batch(_make_batch(schema_id="schema-1"))- process_batch(_make_batch(schema_id="schema-2"))-- assert mock_connect.call_count == 2-- def test_failed_apply_drops_the_cached_connection(self):- conn1, conn2 = MagicMock(), MagicMock()- self.mock_inner.side_effect = [RuntimeError("apply failed"), None]- with self._connect_patch() as mock_connect:- mock_connect.side_effect = [conn1, conn2]- with pytest.raises(RuntimeError):- process_batch(_make_batch(batch_index=1))- process_batch(_make_batch(batch_index=2))-- conn1.close.assert_called_once()- assert mock_connect.call_count == 2-- def test_expired_session_is_replaced(self, monkeypatch):- conn1, conn2 = MagicMock(), MagicMock()- clock = {"now": 1000.0}- monkeypatch.setattr(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.time",- MagicMock(monotonic=lambda: clock["now"]),- )- with self._connect_patch() as mock_connect:- mock_connect.side_effect = [conn1, conn2]- process_batch(_make_batch(batch_index=1))- clock["now"] += 10_000 # far past both idle TTL and absolute age cap- process_batch(_make_batch(batch_index=2))-- conn1.close.assert_called_once()- assert mock_connect.call_count == 2-- def test_absolute_age_cap_survives_steady_reuse(self, monkeypatch):- # The extract-read secret embeds expiring session credentials, so the- # cap must track the ORIGINAL session creation, not the last reuse.- conn1, conn2 = MagicMock(), MagicMock()- clock = {"now": 1000.0}- monkeypatch.setattr(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.time",- MagicMock(monotonic=lambda: clock["now"]),- )- with self._connect_patch() as mock_connect:- mock_connect.side_effect = [conn1, conn2]- for i in range(12): # reuse every 61s: idle TTL never trips, age cap must- process_batch(_make_batch(batch_index=i))- clock["now"] += 61.0-- conn1.close.assert_called_once()- assert mock_connect.call_count == 2-- def test_evict_stale_closes_idle_sessions_without_new_traffic(self, monkeypatch):- # Review finding (Greptile P1 / hex-security): eviction must not depend- # on a later acquire()/store() — a drained group's session would pin a- # duckgres worker indefinitely. The sweeper calls _evict_stale on a- # timer; this exercises it directly with a controlled clock.- conn1 = MagicMock()- clock = {"now": 1000.0}- monkeypatch.setattr(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.time",- MagicMock(monotonic=lambda: clock["now"]),- )- with self._connect_patch() as mock_connect:- mock_connect.return_value = conn1- process_batch(_make_batch(batch_index=1))-- clock["now"] += 91.0- _session_cache._evict_stale()-- conn1.close.assert_called_once()-- def test_store_starts_the_sweeper_thread_once(self):- with self._connect_patch() as mock_connect:- mock_connect.return_value = MagicMock()- process_batch(_make_batch(batch_index=1))- process_batch(_make_batch(batch_index=2))-- assert _session_cache._sweeper_started is True-- def test_org_change_invalidates_the_cached_session(self):- # Review finding (veria): the cache key must include the org so a team- # transferred between organizations can never keep writing through the- # previous org's authenticated connection.- conn1, conn2 = MagicMock(), MagicMock()- with self._connect_patch() as mock_connect:- mock_connect.side_effect = [conn1, conn2]- process_batch(_make_batch(batch_index=1))- self.mock_team.objects.only.return_value.get.return_value.organization_id = "org-b"- process_batch(_make_batch(batch_index=2))-- assert mock_connect.call_count == 2-- def test_per_org_session_cap_evicts_the_oldest_entry(self):- # hex-security follow-up: retained sessions must never accumulate past- # a small per-org bound, even across many sequentially drained groups —- # each cached session pins a duckgres worker.- conns = [MagicMock() for _ in range(5)]- with self._connect_patch() as mock_connect:- mock_connect.side_effect = conns- for i in range(5):- process_batch(_make_batch(schema_id=f"schema-{i}"))-- assert len(_session_cache._entries) == 4- conns[0].close.assert_called_once()- for c in conns[1:]:- c.close.assert_not_called()-- def test_cache_miss_resolves_the_team_once(self):- # greptile follow-up: org resolution feeds both the cache key and the- # connection config — one ORM lookup per batch, not two.- with self._connect_patch() as mock_connect:- mock_connect.return_value = MagicMock()- process_batch(_make_batch(batch_index=1))-- assert self.mock_team.objects.only.return_value.get.call_count == 1---def _existence_conn(exists: bool):- """A mock connection whose LIMIT-0 probe reports existence: it succeeds when- the table exists, and raises duckgres's XX000 "... does not exist" when not."""- conn = MagicMock()- if not exists:- conn.execute.side_effect = psycopg.errors.InternalError_(- "flight execute: ... Catalog Error: Table with name t does not exist!"- )- return conn---class TestTableExistsProbeAndCache:- """The existence check the sink runs every non-first batch: a cheap- single-table LIMIT-0 probe (the whole-catalog information_schema check cost- ~48s under concurrent snapshot commits, prod 2026-07), cached per connection."""-- def test_probe_succeeds_means_exists(self):- assert _table_exists(_existence_conn(True), "s", "t") is True-- def test_probe_not_found_means_absent(self):- assert _table_exists(_existence_conn(False), "s", "t") is False-- def test_other_error_propagates_not_treated_as_absent(self):- # A transient failure must NOT be read as "table absent" (that would pick- # the create path); only DuckDB's table-missing message means absent.- conn = MagicMock()- conn.execute.side_effect = psycopg.errors.InternalError_("flight execute: rpc error: Unavailable")- with pytest.raises(psycopg.Error):- _table_exists(conn, "s", "t")-- def test_missing_schema_error_propagates_not_treated_as_table_absent(self):- # A bare "does not exist" match would swallow a missing schema/catalog/- # secret and wrongly pick the create path; only "Table with name ..." is- # absent. (Greptile P1.)- conn = MagicMock()- conn.execute.side_effect = psycopg.errors.InternalError_(- "flight execute: ... Catalog Error: Schema with name s does not exist!"- )- with pytest.raises(psycopg.Error):- _table_exists(conn, "s", "t")-- def test_second_check_on_same_connection_skips_the_probe(self):- conn = _existence_conn(True)- assert _table_exists(conn, "posthog_data_imports_team_1", "customers") is True- assert _table_exists(conn, "posthog_data_imports_team_1", "customers") is True- assert conn.execute.call_count == 1 # probed once despite two checks-- def test_distinct_tables_each_probe_once(self):- conn = _existence_conn(True)- _table_exists(conn, "s", "a")- _table_exists(conn, "s", "b")- _table_exists(conn, "s", "a")- assert conn.execute.call_count == 2-- def test_separate_connections_do_not_share_the_cache(self):- c1, c2 = _existence_conn(True), _existence_conn(True)- _table_exists(c1, "s", "t")- _table_exists(c2, "s", "t")- assert c1.execute.call_count == 1- assert c2.execute.call_count == 1-- def test_absent_table_is_not_cached(self):- # A negative must be re-checked: the table may be created between batches- # (the create path), so caching "does not exist" would wrongly skip a- # later insert/merge onto the now-existing table.- conn = _existence_conn(False)- assert _table_exists(conn, "s", "t") is False- assert _table_exists(conn, "s", "t") is False- assert conn.execute.call_count == 2diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.pyindex 22dcf9a4ccdf..ba9932a8807a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py@@ -49,8 +49,7 @@ PARTITION_PRUNING_INTERVAL = "14 days"# margin absorbs clock skew and sweep timing. Applies only to the outer claim# candidates and the recovery sweep — never to the head-of-line/failed-run/# schema-busy gates, which must keep seeing rows aged past this window for as-# long as they exist. The duckgres claim path (duckgres/jobs_db.py) has a-# similar exposure but is deliberately out of scope here.+# long as they exist.CLAIM_ELIGIBILITY_INTERVAL = "6 days 12 hours"# Quiet time (no batch inserts or status writes) before lock takeover treats a run as@@ -389,21 +388,6 @@ def _stale_executing_sql(scope_sql: str = "") -> str:"""-# Retained for the duckgres sink, which still coordinates via session advisory-# locks (see duckgres/jobs_db.py). The delta queue now uses leases instead.-async def unlock_advisory_locks(- conn: psycopg.AsyncConnection[Any],- *,- batches: list[PendingBatch],- namespace: int,-) -> None:- for batch in batches:- await conn.execute(- "SELECT pg_advisory_unlock(%(ns)s, hashtext(%(key)s))",- {"ns": namespace, "key": f"{batch.team_id}:{batch.schema_id}"},- )--@dataclass(frozen=True, slots=True)class PendingBatch:"""A batch row fetched from the queue, ready to be processed by the consumer."""@@ -868,9 +852,8 @@ class BatchQueue:) -> bool:"""Check whether ``owner_token`` still holds a live group lease for (team_id, schema_id).- Named ``verify_advisory_lock`` for interface continuity with the- consumer engine and the duckgres sink; ownership is now a lease row, not- a session advisory lock.+ Named ``verify_advisory_lock`` for interface continuity with the consumer engine;+ ownership is a lease row, not a session advisory lock."""async with conn.cursor() as cur:await cur.execute(diff --git a/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py b/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.pyindex 2be66bd7a715..a15bc9326d50 100644--- a/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py+++ b/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py@@ -24,24 +24,17 @@ from products.warehouse_sources.backend.models.external_data_job import Externalfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import sync_lock-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (- DUCKGRES_LEASE_TABLE,- DUCKGRES_STATUS_TABLE,+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ LEASE_TABLE,+ STATUS_TABLE,)--# The duckgres test module's DDL is a superset of the delta queue's (both status-# and lease tables), which the --sink duckgres tests need.-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.test_jobs_db import (+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (_BATCH_DEFAULTS,_ensure_tables,_get_test_database_url,_truncate_tables,)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (- BATCH_TABLE,- LEASE_TABLE,- STATUS_TABLE,-)pytestmark = [pytest.mark.django_db]@@ -367,13 +360,6 @@ class TestTargetingValidation:pytest.param(["release-locks", "--team-id", "1", "--leases-only", "--redis-only"], id="release_both_only_flags"),- pytest.param(- ["fail-run", "--sink", "duckgres", "--team-id", "1", "--cancel-workflow"],- id="cancel_workflow_duckgres",- ),- pytest.param(- ["release-locks", "--sink", "duckgres", "--team-id", "1", "--redis-only"], id="redis_only_duckgres"- ),],)def test_invalid_targeting_raises(self, args, queue_conn, fake_redis):@@ -534,8 +520,8 @@ class TestCheckMismatches:# repair-time re-check sees live work and leaves the job alone.real_collect = Command._collect_fail_targets- def collect_then_enqueue(self, conn, scope, *, queue, include_job_only):- targets = real_collect(self, conn, scope, queue=queue, include_job_only=include_job_only)+ def collect_then_enqueue(self, conn, scope, *, queue):+ targets = real_collect(self, conn, scope, queue=queue)_insert_batch(queue_conn,team_id=team.pk,@@ -580,92 +566,3 @@ class TestCheckMismatches:assert stripe_run in outassert pg_run not in out-- def test_duckgres_sink_is_rejected(self, queue_conn, fake_redis):- with pytest.raises(CommandError, match="delta sink"):- _call("check-mismatches", "--sink", "duckgres", "--team-id", "1")---def _seed_duckgres_run(- conn: psycopg.Connection[Any],- *,- team,- schema: ExternalDataSchema,- job: ExternalDataJob,- run_uuid: str,-) -> dict[str, str]:- """A run mid-way through the duckgres sink: one batch fully applied, one the- sink hasn't claimed, one retrying, and one whose delta load isn't done yet."""- common = {- "team_id": team.pk,- "schema_id": str(schema.id),- "source_id": str(schema.source_id),- "job_id": str(job.id),- "run_uuid": run_uuid,- "metadata": {"workflow_run_id": job.workflow_run_id},- }- applied = _insert_batch(conn, **common, batch_index=0)- _set_status(conn, applied, "succeeded")- _set_status(conn, applied, "succeeded", table=DUCKGRES_STATUS_TABLE)- unclaimed = _insert_batch(conn, **common, batch_index=1)- _set_status(conn, unclaimed, "succeeded")- retrying = _insert_batch(conn, **common, batch_index=2)- _set_status(conn, retrying, "succeeded")- _set_status(conn, retrying, "waiting_retry", table=DUCKGRES_STATUS_TABLE)- delta_pending = _insert_batch(conn, **common, batch_index=3)- _set_status(conn, delta_pending, "executing")- return {"applied": applied, "unclaimed": unclaimed, "retrying": retrying, "delta_pending": delta_pending}---class TestDuckgresSink:- def test_fail_run_fails_pending_duckgres_batches_without_touching_delta_or_job(self, team, queue_conn, fake_redis):- _, schema, job = _create_pipeline(team)- run_uuid = str(uuid4())- _seed_duckgres_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid)- _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False, table=DUCKGRES_LEASE_TABLE)- _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)-- out = _call(- "fail-run",- "--sink",- "duckgres",- "--team-id",- str(team.pk),- "--schema-id",- str(schema.id),- "--live-run",- "--yes",- )-- # only the duckgres-pending batches (unclaimed + retrying) get duckgres failed rows;- # the applied batch and the delta-still-executing batch stay untouched- assert _failed_status_counts_by_run(queue_conn, table=DUCKGRES_STATUS_TABLE) == {run_uuid: 2}- assert _failed_status_counts_by_run(queue_conn) == {} # delta statuses untouched- job.refresh_from_db()- assert job.status == ExternalDataJob.Status.RUNNING # the duckgres sink doesn't own the job- assert _lease_count(queue_conn, str(schema.id), table=DUCKGRES_LEASE_TABLE) == 0- assert _lease_count(queue_conn, str(schema.id)) == 1 # delta lease untouched- assert "marked 2 pending batch(es) failed" in out-- def test_release_locks_releases_only_duckgres_leases(self, team, queue_conn, fake_redis):- _, schema, _ = _create_pipeline(team)- _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False, table=DUCKGRES_LEASE_TABLE)- _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)-- _call("release-locks", "--sink", "duckgres", "--team-id", str(team.pk), "--live-run", "--yes")-- assert _lease_count(queue_conn, str(schema.id), table=DUCKGRES_LEASE_TABLE) == 0- assert _lease_count(queue_conn, str(schema.id)) == 1-- def test_status_reports_duckgres_sections(self, team, queue_conn, fake_redis):- _, schema, job = _create_pipeline(team)- run_uuid = str(uuid4())- batches = _seed_duckgres_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid)- _set_status(queue_conn, batches["retrying"], "executing", table=DUCKGRES_STATUS_TABLE)- _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False, table=DUCKGRES_LEASE_TABLE)-- out = _call("status", "--sink", "duckgres", "--team-id", str(team.pk), "--stale-grace-seconds", "0")-- assert run_uuid in out- assert "unclaimed: 1" in out # delta-succeeded batch the duckgres sink hasn't claimed- assert "Redis pipeline locks" not in out # delta-only sectiondiff --git a/products/warehouse_sources_queue/backend/migrations/0007_remove_duckgres_batch_sink_models.py b/products/warehouse_sources_queue/backend/migrations/0007_remove_duckgres_batch_sink_models.pynew file mode 100644index 000000000000..7ef3855b2425--- /dev/null+++ b/products/warehouse_sources_queue/backend/migrations/0007_remove_duckgres_batch_sink_models.py@@ -0,0 +1,24 @@+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources_queue", "0006_sourcebatch_latest_state"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.DeleteModel(+ name="SourceBatchDuckgresApply",+ ),+ migrations.DeleteModel(+ name="SourceBatchDuckgresStatus",+ ),+ migrations.DeleteModel(+ name="SourceDuckgresGroupLease",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txtindex 0568b7205b5c..d5830aa2f289 100644--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_sourcebatch_latest_state+0007_remove_duckgres_batch_sink_modelsdiff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.pyindex 9d471d4ee4fb..d16276afca7c 100644--- a/products/warehouse_sources_queue/backend/models.py+++ b/products/warehouse_sources_queue/backend/models.py@@ -1,6 +1,5 @@from django.db import models-from posthog.models.scoping.product_mixin import ProductTeamModelfrom posthog.models.utils import UUIDModel, sane_repr@@ -120,35 +119,6 @@ class SourceBatchStatus(UUIDModel):]-class SourceBatchDuckgresStatus(UUIDModel):- class State(models.TextChoices):- EXECUTING = "executing", "executing"- SUCCEEDED = "succeeded", "succeeded"- WAITING_RETRY = "waiting_retry", "waiting_retry"- FAILED = "failed", "failed"-- batch = models.ForeignKey(- SourceBatch,- on_delete=models.DO_NOTHING,- db_constraint=False,- related_name="duckgres_statuses",- )- job_state = models.CharField(max_length=32, choices=State.choices)- attempt = models.SmallIntegerField(default=0)- exec_time = models.DateTimeField(null=True, blank=True)- error_response = models.JSONField(null=True, blank=True)- created_at = models.DateTimeField(auto_now_add=True)-- class Meta:- db_table = "sourcebatchduckgresstatus"- indexes = [- models.Index(- fields=["batch_id", "-created_at", "-id", "job_state"],- name="sbdgs_batch_desc_state_idx",- ),- ]--class SourceGroupLease(models.Model):"""Lease-based mutual exclusion for processing a (team_id, schema_id) group.@@ -177,58 +147,3 @@ class SourceGroupLease(models.Model):indexes = [models.Index(fields=["expires_at"], name="sgl_expires_at_idx"),]---class SourceDuckgresGroupLease(ProductTeamModel):- """Lease-based mutual exclusion for the duckgres sink's (team_id, schema_id) groups.-- Same mechanics as [SourceGroupLease], but a separate table: both consumers- process the same groups independently and must never contend for one lease- row. Replaces the sink's session-scoped advisory lock, which could be- orphaned indefinitely on SIGKILL or a lingering pgbouncer session. All- access is raw SQL in ``duckgres/jobs_db.py``; this model exists for- migration/introspection.- """-- schema_id = models.CharField(max_length=200)- owner_token = models.CharField(max_length=64, help_text="Per-pod identity (uuid4) of the current lease holder.")- expires_at = models.DateTimeField()- acquired_at = models.DateTimeField(auto_now_add=True)- updated_at = models.DateTimeField(auto_now=True)-- __repr__ = sane_repr("team_id", "schema_id", "owner_token", "expires_at")-- class Meta:- db_table = "sourceduckgresgrouplease"- constraints = [- models.UniqueConstraint(fields=["team_id", "schema_id"], name="sdgl_team_schema_uniq"),- ]- indexes = [- models.Index(fields=["expires_at"], name="sdgl_expires_at_idx"),- ]---class SourceBatchDuckgresApply(ProductTeamModel, UUIDModel):- schema_id = models.CharField(max_length=200)- run_uuid = models.CharField(max_length=200)- batch_index = models.IntegerField()- batch = models.ForeignKey(- SourceBatch,- on_delete=models.DO_NOTHING,- db_constraint=False,- related_name="duckgres_applies",- )- row_count = models.IntegerField()- created_at = models.DateTimeField(auto_now_add=True)-- class Meta:- db_table = "sourcebatchduckgresapply"- constraints = [- models.UniqueConstraint(- fields=["team_id", "schema_id", "run_uuid", "batch_index"],- name="sbdga_unique_batch_apply",- )- ]- indexes = [- models.Index(fields=["team_id", "schema_id", "run_uuid"], name="sbdga_run_idx"),- ]diff --git a/products/warehouse_sources_queue/backend/tests/test_models.py b/products/warehouse_sources_queue/backend/tests/test_models.pyindex 2f74a2ecca7d..0039783664fe 100644--- a/products/warehouse_sources_queue/backend/tests/test_models.py+++ b/products/warehouse_sources_queue/backend/tests/test_models.py@@ -1,11 +1,4 @@-from django.db.models import UniqueConstraint--from products.warehouse_sources_queue.backend.models import (- SourceBatch,- SourceBatchDuckgresApply,- SourceBatchDuckgresStatus,- SourceBatchStatus,-)+from products.warehouse_sources_queue.backend.models import SourceBatch, SourceBatchStatusclass TestSourceBatchModel:@@ -28,35 +21,3 @@ class TestSourceBatchStatusModel:def test_batch_fk_has_no_db_constraint(self):field = SourceBatchStatus._meta.get_field("batch")assert not field.db_constraint # type: ignore[attr-defined]---class TestSourceBatchDuckgresStatusModel:- def test_state_choices(self):- values = {c.value for c in SourceBatchDuckgresStatus.State}- assert values == {"executing", "succeeded", "waiting_retry", "failed"}-- def test_db_table(self):- assert SourceBatchDuckgresStatus._meta.db_table == "sourcebatchduckgresstatus"-- def test_batch_fk_has_no_db_constraint(self):- field = SourceBatchDuckgresStatus._meta.get_field("batch")- assert not field.db_constraint # type: ignore[attr-defined]---class TestSourceBatchDuckgresApplyModel:- def test_db_table(self):- assert SourceBatchDuckgresApply._meta.db_table == "sourcebatchduckgresapply"-- def test_batch_fk_has_no_db_constraint(self):- field = SourceBatchDuckgresApply._meta.get_field("batch")- assert not field.db_constraint # type: ignore[attr-defined]-- def test_unique_constraint_matches_apply_key(self):- constraint = next(- constraint- for constraint in SourceBatchDuckgresApply._meta.constraints- if constraint.name == "sbdga_unique_batch_apply"- )-- assert isinstance(constraint, UniqueConstraint)- assert tuple(constraint.fields) == ("team_id", "schema_id", "run_uuid", "batch_index")