:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): sync-type claim filter for v3 loader fleet partitioning (#71972)
estefania0167f1cd6f54
diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.pyindex 519276184594..894dcb4108d3 100644--- a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py@@ -1,6 +1,6 @@import asyncio-from django.core.management.base import BaseCommand+from django.core.management.base import BaseCommand, CommandErrorimport structlog@@ -18,10 +18,25 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load import (process_batch,)+from products.warehouse_sources_queue.backend.models import SourceBatchlogger = structlog.get_logger(__name__)+def parse_sync_types(raw: str | None, flag: str) -> list[str] | None:+ """Parse a comma-separated sync-type list, validated against SourceBatch.SyncType."""+ if raw is None:+ return None+ values = [value.strip() for value in raw.split(",") if value.strip()]+ if not values:+ return None+ valid = set(SourceBatch.SyncType.values)+ invalid = [value for value in values if value not in valid]+ if invalid:+ raise CommandError(f"{flag}: unknown sync type(s) {invalid}; valid: {sorted(valid)}")+ return values++def build_consumer_config(options: dict) -> ConsumerConfig:"""Translate CLI options into a ConsumerConfig.@@ -52,7 +67,12 @@ def build_consumer_config(options: dict) -> ConsumerConfig:return ConsumerConfig(**kwargs)-async def _run_consumer(config: ConsumerConfig, health_reporter) -> None:+async def _run_consumer(+ config: ConsumerConfig,+ health_reporter,+ claim_sync_types: list[str] | None,+ claim_exclude_sync_types: list[str] | None,+) -> None:"""Configure the Temporal-style produce path then run the consumer.`configure_logger` plumbs structlog into a Kafka producer that feeds ClickHouse `log_entries`.@@ -62,7 +82,13 @@ async def _run_consumer(config: ConsumerConfig, health_reporter) -> None:`workflow_id`, `workflow_run_id`, `team_id`, plus the event-level `log_source_id` override)."""configure_logger(loop=asyncio.get_running_loop())- consumer = BatchConsumer(config=config, process_batch=process_batch, health_reporter=health_reporter)+ consumer = BatchConsumer(+ config=config,+ process_batch=process_batch,+ health_reporter=health_reporter,+ claim_sync_types=claim_sync_types,+ claim_exclude_sync_types=claim_exclude_sync_types,+ )await consumer.run()@@ -166,6 +192,24 @@ class Command(BaseCommand):default=None,help="Deprecated, ignored: readers always use the denormalized state columns",)+ # Fleet partitioning: which sourcebatch.sync_type classes this deployment claims+ # and sweeps. Paired deployments must cover every class between them — a class no+ # fleet claims sits in the queue until partition pruning.+ parser.add_argument(+ "--claim-sync-types",+ type=str,+ default=None,+ help="Comma-separated sync types this consumer claims (e.g. 'cdc'). Default: all",+ )+ parser.add_argument(+ "--claim-exclude-sync-types",+ type=str,+ default=None,+ help=(+ "Comma-separated sync types this consumer does NOT claim (e.g. 'cdc'). "+ "Mutually exclusive with --claim-sync-types"+ ),+ )def handle(self, *args, **options):health_port = options["health_port"]@@ -178,6 +222,13 @@ class Command(BaseCommand):"claim_path_legacy_removed", note="--claim-path is ignored; the legacy claim path no longer exists")+ claim_sync_types = parse_sync_types(options.get("claim_sync_types"), "--claim-sync-types")+ claim_exclude_sync_types = parse_sync_types(+ options.get("claim_exclude_sync_types"), "--claim-exclude-sync-types"+ )+ if claim_sync_types and claim_exclude_sync_types:+ raise CommandError("--claim-sync-types and --claim-exclude-sync-types are mutually exclusive")+logger.info("warehouse_sources_load_starting",max_concurrency=config.max_concurrency,@@ -192,9 +243,11 @@ class Command(BaseCommand):lease_ttl=config.lease_ttl_seconds,recovery_grace=config.recovery_grace_seconds,poll_failure_liveness_threshold=config.poll_failure_liveness_threshold,+ claim_sync_types=claim_sync_types,+ claim_exclude_sync_types=claim_exclude_sync_types,)health_state = HealthState(timeout_seconds=health_timeout)start_health_server(port=health_port, health_state=health_state)- asyncio.run(_run_consumer(config, health_state.report_healthy))+ asyncio.run(_run_consumer(config, health_state.report_healthy, claim_sync_types, claim_exclude_sync_types))diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex ed1ca276fd1b..bbe57fafd177 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -96,7 +96,16 @@ class DeltaBatchConsumerAdapter:waiting_retry_state: str = SourceBatchStatus.State.WAITING_RETRY.valueper_group_connections: bool = True- def __init__(self) -> None:+ def __init__(+ self,+ *,+ claim_sync_types: list[str] | None = None,+ claim_exclude_sync_types: list[str] | None = None,+ ) -> None:+ # Fleet partition: the sync_type classes this consumer claims and sweeps.+ # None/None (the default) means the whole queue — a single-fleet deployment.+ self._claim_sync_types = claim_sync_types+ self._claim_exclude_sync_types = claim_exclude_sync_types# job_id -> (is_dead, checked_at via time.monotonic())self._job_dead_cache: dict[str, tuple[bool, float]] = {}@@ -115,6 +124,8 @@ class DeltaBatchConsumerAdapter:limit=limit,retry_backoff_base_seconds=retry_backoff_base_seconds,lease_ttl_seconds=lease_ttl_seconds,+ sync_types=self._claim_sync_types,+ exclude_sync_types=self._claim_exclude_sync_types,)async def unlock(@@ -238,7 +249,12 @@ class DeltaBatchConsumerAdapter:) -> list[PendingBatch]:# keep_locks is meaningless for the lease sink: get_stale_executing holds# no locks and the lease LEFT JOIN already excludes live groups.- return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)+ return await BatchQueue.get_stale_executing(+ conn,+ grace_seconds=grace_seconds,+ sync_types=self._claim_sync_types,+ exclude_sync_types=self._claim_exclude_sync_types,+ )async def reconcile_failed_runs(self,@@ -429,6 +445,8 @@ class BatchConsumer(SharedBatchConsumer):config: ConsumerConfig,process_batch: DeltaProcessBatchFn,health_reporter: Callable[[], None] | None = None,+ claim_sync_types: list[str] | None = None,+ claim_exclude_sync_types: list[str] | None = None,) -> None:async def process_with_ownership_check(batch: PendingBatch) -> None:await process_batch(batch, self._make_verify_ownership(batch))@@ -436,7 +454,10 @@ class BatchConsumer(SharedBatchConsumer):super().__init__(config=config,process_batch=process_with_ownership_check,- adapter=DeltaBatchConsumerAdapter(),+ adapter=DeltaBatchConsumerAdapter(+ claim_sync_types=claim_sync_types,+ claim_exclude_sync_types=claim_exclude_sync_types,+ ),health_reporter=health_reporter,)diff --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 16863b2f07b6..1890a10d7270 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@@ -96,6 +96,31 @@ def pending_batch_predicate(status_alias: str) -> str:return f"({status_alias}.batch_id IS NULL OR {status_alias}.job_state IN ('waiting', 'waiting_retry', 'executing'))"+def sync_type_scope_sql(+ *,+ sync_types: list[str] | None = None,+ exclude_sync_types: list[str] | None = None,+) -> tuple[str, dict[str, Any]]:+ """Optional AND-clause partitioning claim/sweep work by ``sourcebatch.sync_type``.++ Lets a consumer fleet own a subset of the queue (e.g. a CDC-only deployment) while a+ sibling fleet runs with the complement. The clause may only ever scope *which rows a+ fleet claims or sweeps* — never the run/failed/schema-busy gates, which must keep+ seeing every class so cross-class runs of one (team_id, schema_id) still serialize+ (a CDC schema's initial snapshot enqueues ``full_refresh`` batches).+ """+ if sync_types and exclude_sync_types:+ raise ValueError("sync_types and exclude_sync_types are mutually exclusive")+ if sync_types:+ return "AND b.sync_type = ANY(%(claim_sync_types)s)", {"claim_sync_types": list(sync_types)}+ if exclude_sync_types:+ return (+ "AND b.sync_type != ALL(%(claim_exclude_sync_types)s)",+ {"claim_exclude_sync_types": list(exclude_sync_types)},+ )+ return "", {}++def build_status_dual_write_sql(*, with_batch_created_at: bool) -> str:"""Single-statement status INSERT + denormalized-state UPDATE (atomic under autocommit).@@ -174,13 +199,18 @@ FAIL_RUN_SCOPED_SQL = _bulk_fail_dual_write_sql()-def _state_claim_candidates_sql() -> str:+def _state_claim_candidates_sql(sync_type_scope: str = "") -> str:"""Claimable-batch candidates read from the denormalized state columns.The claimable scan and every NOT EXISTS gate are answered by the partialindexes (sb_claimable_idx, sb_run_gate_idx, sb_schema_busy_idx), so thework tracks the claimable set instead of everything retained. 'pending'means no status row yet; 'waiting' is deliberately not claimable.++ ``sync_type_scope`` (from :func:`sync_type_scope_sql`) narrows only the outer+ candidate set to this fleet's classes. It must never be applied inside the+ NOT EXISTS gates below: they have to see other fleets' batches so one+ schema's runs stay mutually exclusive across fleets."""return f"""SELECT@@ -194,6 +224,7 @@ def _state_claim_candidates_sql() -> str:FROM {BATCH_TABLE} bWHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ {sync_type_scope}AND (b.latest_state = 'pending'OR (@@ -474,6 +505,8 @@ class BatchQueue:limit: int = 50,retry_backoff_base_seconds: int = 0,lease_ttl_seconds: int = LEASE_TTL_SECONDS,+ sync_types: list[str] | None = None,+ exclude_sync_types: list[str] | None = None,) -> list[PendingBatch]:"""Fetch unprocessed batches whose (team_id, schema_id) group lease is claimable by ``owner_token``.@@ -526,8 +559,15 @@ class BatchQueue:dead weight and fleet concurrency collapses to roughly one window's worth.Own-leased groups stay in the window so a pod can keep draining a group italready holds.++ ``sync_types`` / ``exclude_sync_types`` partition the queue between consumer+ fleets (see :func:`sync_type_scope_sql`); leases are shared state, so fleets+ with overlapping scopes still never process one group concurrently."""- candidates_sql = _state_claim_candidates_sql()+ sync_type_scope, scope_params = sync_type_scope_sql(+ sync_types=sync_types, exclude_sync_types=exclude_sync_types+ )+ candidates_sql = _state_claim_candidates_sql(sync_type_scope)async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""@@ -573,7 +613,13 @@ class BatchQueue:JOIN claimed USING (team_id, schema_id)ORDER BY c.created_at ASC, c.batch_index ASC""",- {"limit": limit, "backoff": retry_backoff_base_seconds, "owner": owner_token, "ttl": lease_ttl_seconds},+ {+ "limit": limit,+ "backoff": retry_backoff_base_seconds,+ "owner": owner_token,+ "ttl": lease_ttl_seconds,+ **scope_params,+ },)rows = await cur.fetchall()return [PendingBatch(**row) for row in rows]@@ -691,6 +737,8 @@ class BatchQueue:conn: psycopg.AsyncConnection[Any],*,grace_seconds: int = 0,+ sync_types: list[str] | None = None,+ exclude_sync_types: list[str] | None = None,) -> list[PendingBatch]:"""Find batches stuck in 'executing' whose group lease is absent or expired (previous pod gone).@@ -703,9 +751,17 @@ class BatchQueue:``grace_seconds`` requires the 'executing' status row to be older thanthis threshold before the batch is considered orphaned.++ ``sync_types`` / ``exclude_sync_types`` keep a fleet's sweep on its own+ classes: each fleet judges staleness against its own grace, so a+ short-grace fleet must never re-queue a batch a long-grace fleet still+ considers mid-write."""+ sync_type_scope, scope_params = sync_type_scope_sql(+ sync_types=sync_types, exclude_sync_types=exclude_sync_types+ )async with conn.cursor(row_factory=dict_row) as cur:- await cur.execute(_stale_executing_sql(), {"grace": grace_seconds})+ await cur.execute(_stale_executing_sql(sync_type_scope), {"grace": grace_seconds, **scope_params})rows = await cur.fetchall()return [PendingBatch(**row) for row in rows]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.pyindex f32c4218002a..64e363ab1337 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py@@ -1105,3 +1105,52 @@ class TestClaimGates:finally:await conn.execute("SET enable_seqscan = on")assert "sb_claimable_idx" in plan++[email protected]_db(transaction=True)+class TestSyncTypeFleetPartition:+ @pytest.mark.asyncio+ async def test_allowlist_and_denylist_fleets_partition_the_queue(self, conn, conn_b):+ # Two fleets with complementary scopes must claim disjoint sets that+ # together cover every class — a class neither fleet claims would sit in+ # the queue until partition pruning.+ cdc_bid = await _insert_batch(conn, team_id=1, schema_id="cdc-s", run_uuid="cdc-run", sync_type="cdc")+ fr_bid = await _insert_batch(conn, team_id=2, schema_id="fr-s", run_uuid="fr-run", sync_type="full_refresh")+ inc_bid = await _insert_batch(conn, team_id=3, schema_id="inc-s", run_uuid="inc-run", sync_type="incremental")++ cdc_fleet = await _claim(conn, owner=OWNER_A, sync_types=["cdc"])+ general_fleet = await _claim(conn_b, owner=OWNER_B, exclude_sync_types=["cdc"])++ assert [str(b.id) for b in cdc_fleet] == [cdc_bid]+ assert {str(b.id) for b in general_fleet} == {fr_bid, inc_bid}++ @pytest.mark.asyncio+ async def test_filter_leaves_schema_busy_gate_class_blind(self, conn):+ # A CDC schema's initial snapshot enqueues full_refresh batches, which run+ # on the other fleet. While one is executing, a cdc-scoped claim must still+ # see the schema as busy — scoping the busy gate itself would let two+ # fleets write the same schema's table concurrently.+ snapshot_bid = await _insert_batch(conn, schema_id="S", run_uuid="snapshot-run", sync_type="full_refresh")+ await _insert_batch(conn, schema_id="S", run_uuid="cdc-run", sync_type="cdc")+ control_bid = await _insert_batch(conn, team_id=2, schema_id="T", run_uuid="t-run", sync_type="cdc")+ await BatchQueue.update_status(conn, batch_id=snapshot_bid, job_state="executing", attempt=1)++ batches = await _claim(conn, sync_types=["cdc"])++ assert [str(b.id) for b in batches] == [control_bid]++ @pytest.mark.asyncio+ async def test_stale_sweep_scoped_to_fleet_classes(self, conn):+ # Each fleet judges staleness against its own recovery grace, so its sweep+ # must only recover its own classes: an unscoped short-grace sweep would+ # re-queue a batch the other fleet still considers mid-write.+ cdc_bid = await _insert_batch(conn, schema_id="cdc-s", run_uuid="cdc-run", sync_type="cdc")+ fr_bid = await _insert_batch(conn, team_id=2, schema_id="fr-s", run_uuid="fr-run", sync_type="full_refresh")+ await _insert_backdated_executing(conn, batch_id=cdc_bid, age_seconds=120)+ await _insert_backdated_executing(conn, batch_id=fr_bid, age_seconds=120)++ cdc_stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60, sync_types=["cdc"])+ all_stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60)++ assert [str(b.id) for b in cdc_stale] == [cdc_bid]+ assert {str(b.id) for b in all_stale} == {cdc_bid, fr_bid}diff --git a/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.pyindex 4d25b93ed587..b75d26a7f5d9 100644--- a/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py@@ -1,8 +1,13 @@+import pytest++from django.core.management.base import CommandError+from parameterized import parameterizedfrom products.warehouse_sources.backend.management.commands.run_warehouse_sources_load import (Command,build_consumer_config,+ parse_sync_types,)@@ -52,3 +57,24 @@ class TestBuildConsumerConfig:config = build_consumer_config(_parse_options(["--recovery-grace", "900"]))assert config.lease_ttl_seconds == 900+++class TestParseSyncTypes:+ @parameterized.expand(+ [+ (None, None),+ ("", None),+ (" , ", None),+ ("cdc", ["cdc"]),+ ("cdc, append", ["cdc", "append"]),+ ]+ )+ def test_parses_comma_separated_values(self, raw: str | None, expected: list[str] | None):+ assert parse_sync_types(raw, "--claim-sync-types") == expected++ def test_unknown_sync_type_fails_startup(self):+ # A typo'd Helm value (e.g. 'CDC') must crash the pod at startup — accepted+ # silently, it would build a filter matching nothing and the fleet would idle+ # while its classes pile up in the queue.+ with pytest.raises(CommandError, match="unknown sync type"):+ parse_sync_types("CDC", "--claim-sync-types")