Skip to content

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

perf(data-warehouse): coalesce loader batches across consecutive runs (#107907)

Tom Owers5082c9deb534
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.py
index d11ff667c4a5..d6ad4ec80312 100644
--- a/posthog/settings/data_warehouse.py
+++ b/posthog/settings/data_warehouse.py
@@ -168,3 +168,23 @@ WAREHOUSE_SOURCES_DATABASE_URL: str = (
# Warehouse-pipeline and cyclotron Kafka config live in `posthog/settings/kafka.py`
# (profiles `warehouse_sources` and `cyclotron`) — read from `settings.KAFKA_PROFILES[...]`
# or via the back-compat top-level names that settings/kafka.py exposes.
+
+# Bounds on a set of queued batches the V3 loader writes to a Delta table as one commit. The loader
+# holds the whole set decoded in Arrow, then copies it once more while it deduplicates and partitions,
+# so a set must stay inside the memory slice the deltalite governor sizes per concurrent upsert
+# (memory_governor.py): with a 29 GiB pod, 16 groups in flight and a 2 GiB reserve, that slice is
+# about 1.3 GiB, of which 750 MiB goes to four partition workers. The row cap equals one extraction
+# chunk, the largest single batch the loader already takes, and the byte cap counts parquet on disk,
+# which decodes to Arrow several times its size. The count cap is only a backstop.
+DATA_WAREHOUSE_V3_COALESCE_MAX_BATCHES = get_from_env("DATA_WAREHOUSE_V3_COALESCE_MAX_BATCHES", 128, type_cast=int)
+DATA_WAREHOUSE_V3_COALESCE_MAX_ROWS = get_from_env("DATA_WAREHOUSE_V3_COALESCE_MAX_ROWS", 500_000, type_cast=int)
+DATA_WAREHOUSE_V3_COALESCE_MAX_BYTES = get_from_env(
+ "DATA_WAREHOUSE_V3_COALESCE_MAX_BYTES", 64 * 1024 * 1024, type_cast=int
+)
+# A set may span consecutive runs of one schema. Off keeps every set inside one run. Off by default
+# until every loader pod runs a build that reads the `members` commit tag: an older pod that
+# redelivers a later run's member of a cross-run set cannot find that member's commit, and on an
+# append table that loads its rows a second time.
+DATA_WAREHOUSE_V3_COALESCE_ACROSS_RUNS = get_from_env(
+ "DATA_WAREHOUSE_V3_COALESCE_ACROSS_RUNS", False, type_cast=str_to_bool
+)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
index 302cbc97ef99..fc1adaa2d525 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
@@ -141,20 +141,30 @@ def commit_matches(commit: dict[str, Any], match: dict[str, str]) -> bool:
return any(all(layout.get(k) == v for k, v in match.items()) for layout in _commit_metadata_layouts(commit))
+def commit_members_tag(members: Sequence[tuple[str, int]]) -> str:
+ """The `members` commit tag for a set that spans runs: `run_uuid:batch_index` per member."""
+ return ",".join(f"{run_uuid}:{batch_index}" for run_uuid, batch_index in members)
+
+
def commit_covers_batch(commit: dict[str, Any], run_uuid: str, batch_index: int) -> bool:
"""Whether this commit wrote `batch_index` of `run_uuid`, alone or as one member of a set.
- A write of several consecutive batches is tagged with the first index under `batch_index` and
- every member under `batch_indexes`, so a member's redelivery has to look in both.
+ A write of several batches is tagged with the head's run and index under `run_uuid` and
+ `batch_index`, the head run's members under `batch_indexes`, and every member of every run under
+ `members` when the set spans runs, so a member's redelivery has to look in all three.
"""
wanted = str(batch_index)
+ wanted_member = f"{run_uuid}:{wanted}"
for layout in _commit_metadata_layouts(commit):
+ members = layout.get("members")
+ if isinstance(members, str) and wanted_member in members.split(","):
+ return True
if layout.get("run_uuid") != run_uuid:
continue
if layout.get("batch_index") == wanted:
return True
- members = layout.get("batch_indexes")
- if isinstance(members, str) and wanted in members.split(","):
+ indexes = layout.get("batch_indexes")
+ if isinstance(indexes, str) and wanted in indexes.split(","):
return True
return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
index 71c3988ca18b..a2d62a9926e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
@@ -453,7 +453,7 @@ class BatchConsumer:
) -> None:
self._config = config
self._process_batch = process_batch
- # Loads several consecutive batches of one run in one write; None keeps every batch single.
+ # Loads several consecutive batches in one write; None keeps every batch single.
self._process_batches = process_batches
self._adapter = adapter
# Per-pod identity for group-lease ownership. A new token each start means
@@ -1195,7 +1195,8 @@ class BatchConsumer:
return await self._process_single_inner(batch, attempt, lock_conn)
async def _process_set(self, batches: list[PendingBatch], lock_conn: psycopg.AsyncConnection[Any] | None) -> bool:
- """Load several consecutive batches of one run as one write. Returns True only on success.
+ """Load several consecutive batches, of one run or of consecutive runs, as one write.
+ Returns True only on success.
Every constituent gets the same status transitions a single batch would, so recovery,
the claim gates and the reconcile sweeps see nothing new. Anything that stops the set
@@ -1207,6 +1208,9 @@ class BatchConsumer:
assert self._process_batches is not None
head = batches[0]
attempts = {batch.id: batch.latest_attempt + 1 for batch in batches}
+ run_uuids = list(dict.fromkeys(batch.run_uuid for batch in batches))
+ row_count = sum(batch.row_count for batch in batches)
+ byte_size = sum(batch.byte_size for batch in batches)
if any(attempt > self._config.max_attempts for attempt in attempts.values()):
return await self._process_singly(batches, lock_conn, spent_attempt=False)
@@ -1222,7 +1226,11 @@ class BatchConsumer:
self._event("batch_set_picked_up"),
batch_ids=[batch.id for batch in batches],
run_uuid=head.run_uuid,
+ run_uuids=run_uuids,
batch_indexes=[batch.batch_index for batch in batches],
+ batch_count=len(batches),
+ row_count=row_count,
+ byte_size=byte_size,
is_final_batch=batches[-1].is_final_batch,
resource_name=head.resource_name,
)
@@ -1255,6 +1263,7 @@ class BatchConsumer:
logger.warning(
self._event("batch_set_failed_loading_singly"),
run_uuid=head.run_uuid,
+ run_uuids=run_uuids,
batch_indexes=[batch.batch_index for batch in batches],
error=str(err),
error_type=type(err).__name__,
@@ -1282,10 +1291,17 @@ class BatchConsumer:
)
self._metrics.batches_processed_total.labels(status="success").inc()
self._metrics.coalesced_sets_total.labels(outcome="success").inc()
+ self._metrics.coalesced_set_batches.observe(len(batches))
+ self._metrics.coalesced_set_runs.observe(len(run_uuids))
+ self._metrics.coalesced_set_rows.observe(row_count)
logger.info(
self._event("batch_set_processed_ok"),
run_uuid=head.run_uuid,
+ run_uuids=run_uuids,
batch_indexes=[batch.batch_index for batch in batches],
+ batch_count=len(batches),
+ row_count=row_count,
+ byte_size=byte_size,
is_final_batch=batches[-1].is_final_batch,
duration_seconds=round(duration, 3),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/coalescing.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/coalescing.py
new file mode 100644
index 000000000000..9666b70f6bf8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/coalescing.py
@@ -0,0 +1,207 @@
+"""Which queued batches the Delta sink may load as one commit.
+
+The consumer plans sets from the batches it claimed, in claim order, and the processor checks a
+set once more before it writes. Both read the rules from here so they cannot drift apart.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import TYPE_CHECKING
+
+from django.conf import settings
+
+from posthog.dataclasses import frozen
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import (
+ ExportSignalMessage,
+ )
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ PendingBatch,
+ )
+
+# CDC batches resolve positions against the table between writes, and a batch bound for external
+# destinations is delivered per batch, so neither is folded into a set.
+COALESCABLE_SYNC_TYPES: frozenset[str] = frozenset({"incremental", "append", "full_refresh"})
+# A full refresh starts over at batch 0 and appends after it, so its runs never share a write.
+CROSS_RUN_SYNC_TYPES: frozenset[str] = frozenset({"incremental", "append"})
+
+
+@frozen
+class LoadShape:
+ """The load configuration every member of a set must share.
+
+ A set is written under its head's configuration, so a member whose keys, partitioning or
+ first-sync flag differ would be merged the wrong way.
+ """
+
+ sync_type: str
+ resource_name: str
+ primary_keys: tuple[str, ...] | None
+ partition_keys: tuple[str, ...] | None
+ partition_count: int | None
+ partition_size: int | None
+ partition_mode: str | None
+ partition_format: str | None
+ is_first_ever_sync: bool
+ cdc_write_mode: str | None
+ has_destinations: bool
+
+
+@frozen
+class CoalesceMember:
+ """What the rules need to know about one queued batch."""
+
+ team_id: int
+ schema_id: str
+ run_uuid: str
+ job_id: str
+ batch_index: int
+ is_resume: bool
+ row_count: int
+ byte_size: int
+ shape: LoadShape
+
+ @classmethod
+ def from_batch(cls, batch: PendingBatch) -> CoalesceMember:
+ metadata = batch.metadata
+ return cls(
+ team_id=batch.team_id,
+ schema_id=batch.schema_id,
+ run_uuid=batch.run_uuid,
+ job_id=batch.job_id,
+ batch_index=batch.batch_index,
+ is_resume=batch.is_resume,
+ row_count=batch.row_count,
+ byte_size=batch.byte_size,
+ shape=LoadShape(
+ sync_type=batch.sync_type,
+ resource_name=batch.resource_name,
+ primary_keys=_key_tuple(metadata.get("primary_keys")),
+ partition_keys=_key_tuple(metadata.get("partition_keys")),
+ partition_count=metadata.get("partition_count"),
+ partition_size=metadata.get("partition_size"),
+ partition_mode=metadata.get("partition_mode"),
+ partition_format=metadata.get("partition_format"),
+ is_first_ever_sync=batch.is_first_ever_sync,
+ cdc_write_mode=metadata.get("cdc_write_mode"),
+ has_destinations=bool(batch.destination_ids),
+ ),
+ )
+
+ @classmethod
+ def from_signal(cls, signal: ExportSignalMessage) -> CoalesceMember:
+ return cls(
+ team_id=signal.team_id,
+ schema_id=signal.schema_id,
+ run_uuid=signal.run_uuid,
+ job_id=signal.job_id,
+ batch_index=signal.batch_index,
+ is_resume=signal.is_resume,
+ row_count=signal.row_count,
+ byte_size=signal.byte_size,
+ shape=LoadShape(
+ sync_type=signal.sync_type,
+ resource_name=signal.resource_name,
+ primary_keys=_key_tuple(signal.primary_keys),
+ partition_keys=_key_tuple(signal.partition_keys),
+ partition_count=signal.partition_count,
+ partition_size=signal.partition_size,
+ partition_mode=signal.partition_mode,
+ partition_format=signal.partition_format,
+ is_first_ever_sync=signal.is_first_ever_sync,
+ cdc_write_mode=signal.cdc_write_mode,
+ has_destinations=bool(signal.destination_ids),
+ ),
+ )
+
+
+@frozen
+class CoalesceCaps:
+ """The size a set may grow to. Rows and bytes are the real bounds; the count is a backstop."""
+
+ max_batches: int
+ max_rows: int
+ max_bytes: int
+ across_runs: bool
+
+ @classmethod
+ def from_settings(cls) -> CoalesceCaps:
+ return cls(
+ max_batches=settings.DATA_WAREHOUSE_V3_COALESCE_MAX_BATCHES,
+ max_rows=settings.DATA_WAREHOUSE_V3_COALESCE_MAX_ROWS,
+ max_bytes=settings.DATA_WAREHOUSE_V3_COALESCE_MAX_BYTES,
+ across_runs=settings.DATA_WAREHOUSE_V3_COALESCE_ACROSS_RUNS,
+ )
+
+
+def _key_tuple(keys: Sequence[str] | None) -> tuple[str, ...] | None:
+ return None if keys is None else tuple(keys)
+
+
+def loadable_in_set(shape: LoadShape) -> bool:
+ return shape.sync_type in COALESCABLE_SYNC_TYPES and shape.cdc_write_mode is None and not shape.has_destinations
+
+
+def join_violation(current: Sequence[CoalesceMember], candidate: CoalesceMember) -> str | None:
+ """Why `candidate` cannot follow `current` in one write, or None when it can.
+
+ `current` is in load order. The rules only look at the sequence, never reorder it, so a set's
+ members are written in exactly the order the loader would have taken them one at a time.
+ """
+ tail = current[-1]
+ if not (loadable_in_set(tail.shape) and loadable_in_set(candidate.shape)):
+ return "sync type, CDC mode or destinations are loaded one batch at a time"
+ if (candidate.team_id, candidate.schema_id) != (tail.team_id, tail.schema_id):
+ return "batches belong to different tables"
+ if candidate.shape != tail.shape:
+ return "batches are loaded under different configurations"
+ if candidate.run_uuid == tail.run_uuid:
+ if candidate.job_id != tail.job_id:
+ return "batches of one run belong to different jobs"
+ if candidate.batch_index != tail.batch_index + 1:
+ return "batch indexes are not consecutive"
+ return None
+ if candidate.shape.sync_type not in CROSS_RUN_SYNC_TYPES:
+ return f"{candidate.shape.sync_type} batches never share a write across runs"
+ if candidate.batch_index == 0 and not candidate.is_resume:
+ # A fresh run's first batch may overwrite the table, and only the head of a set overwrites.
+ return "a fresh run starts its own write"
+ if any(member.run_uuid == candidate.run_uuid for member in current):
+ return "a run reappears after another run"
+ return None
+
+
+def extends_set(current: Sequence[CoalesceMember], candidate: CoalesceMember, caps: CoalesceCaps) -> bool:
+ if join_violation(current, candidate) is not None:
+ return False
+ if candidate.run_uuid != current[-1].run_uuid and not caps.across_runs:
+ return False
+ if len(current) >= caps.max_batches:
+ return False
+ rows = sum(member.row_count for member in current) + candidate.row_count
+ size = sum(member.byte_size for member in current) + candidate.byte_size
+ return rows <= caps.max_rows and size <= caps.max_bytes
+
+
+def set_violation(members: Sequence[CoalesceMember]) -> str | None:
+ """Why `members` cannot be one write, or None. Checked by the sink before it reads anything."""
+ if not members:
+ return "the set is empty"
+ if not loadable_in_set(members[0].shape):
+ return "sync type, CDC mode or destinations are loaded one batch at a time"
+ for position in range(1, len(members)):
+ violation = join_violation(members[:position], members[position])
+ if violation is not None:
+ return violation
+ return None
+
+
+def runs_in_order(members: Sequence[CoalesceMember]) -> list[str]:
+ """The distinct runs of a set, in load order."""
+ runs: list[str] = []
+ for member in members:
+ if member.run_uuid not in runs:
+ runs.append(member.run_uuid)
+ return runs
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index 098a72241b86..b33985678eb7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -53,7 +53,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.aut
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.scd2 import Scd2DeltaWriter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import DeltaWriter
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import (
+ DeltaWriter,
+ commit_members_tag,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.hogql_schema import HogQLSchema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
append_partition_key_to_table,
@@ -65,6 +68,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
CoalescingDeclined,
OwnershipLostError,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.coalescing import (
+ CoalesceMember,
+ runs_in_order,
+ set_violation,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.idempotency import (
is_batch_already_processed,
mark_batch_as_processed,
@@ -760,6 +768,83 @@ def _mark_job_failed(export_signal: ExportSignalMessage, error: Exception) -> No
_release_pipeline_lock_for_job(export_signal)
+def _load_job(job_id: str) -> ExternalDataJob:
+ return ExternalDataJob.objects.prefetch_related("schema", "schema__source", "schema__table").get(id=job_id)
+
+
+def _finalize_run(
+ run_signal: ExportSignalMessage,
+ *,
+ job: ExternalDataJob,
+ schema: ExternalDataSchema,
+ delta_table_ref: DeltaTableRef,
+ internal_schema: HogQLSchema,
+ verify_ownership: Callable[[], None] | None,
+) -> None:
+ """Complete one run whose final batch is in the table: post-load, job status, cursor, triggers."""
+ logger.info(
+ "final_batch_received",
+ external_data_job_id=run_signal.job_id,
+ run_uuid=run_signal.run_uuid,
+ batch_index=run_signal.batch_index,
+ total_batches=run_signal.total_batches,
+ total_rows=run_signal.total_rows,
+ cdc_write_mode=run_signal.cdc_write_mode,
+ cdc_table_mode=run_signal.cdc_table_mode,
+ sync_type=run_signal.sync_type,
+ schema_sync_type=schema.sync_type,
+ schema_cdc_table_mode=schema.cdc_table_mode,
+ resource_name=run_signal.resource_name,
+ )
+
+ # Minutes may have passed since the write — re-check before post-load commits and job
+ # completion promote the staged cursor under a new owner.
+ if verify_ownership is not None:
+ verify_ownership()
+
+ report_phase("post_load")
+ prepared_queryable_folder = async_to_sync(run_post_load_operations)(
+ job=job,
+ schema=schema,
+ source=schema.source,
+ delta_table_ref=delta_table_ref,
+ row_count=run_signal.total_rows or 0,
+ table_schema_dict=internal_schema.to_hogql_types(),
+ resource_name=run_signal.resource_name,
+ logger=logger,
+ cdc_write_mode=run_signal.cdc_write_mode,
+ )
+
+ # Post-load can run minutes (compaction, S3 prep) — re-check before
+ # completion promotes the cursor and releases the lock under a new owner.
+ if verify_ownership is not None:
+ verify_ownership()
+
+ report_phase("finalize")
+ _mark_job_completed(run_signal)
+
+ if prepared_queryable_folder:
+ _trigger_ducklake_register_data_imports(run_signal, prepared_queryable_folder)
+
+ _trigger_post_import_workflow(run_signal)
+
+ logger.debug("post_load_operations_complete", external_data_job_id=run_signal.job_id)
+
+ posthoganalytics.capture(
+ distinct_id=get_machine_id(),
+ event="warehouse_v3_load_completed",
+ properties={
+ "team_id": run_signal.team_id,
+ "schema_id": run_signal.schema_id,
+ "source_id": run_signal.source_id,
+ "resource_name": run_signal.resource_name,
+ "sync_type": run_signal.sync_type,
+ "total_batches": run_signal.total_batches,
+ "total_rows": run_signal.total_rows,
+ },
+ )
+
+
def process_message(
message: Any,
progress_callback: Callable[[], None] | None = None,
@@ -792,6 +877,8 @@ def combine_export_signals(signals: list[ExportSignalMessage]) -> ExportSignalMe
It starts where the first batch starts, so batch 0 keeps its overwrite and its partial-loading
semantics, and it ends how the last batch ends, so a final batch in the set completes the run.
+ When the set spans runs the message carries the first run's identity; each run's own completion
+ comes from `final_run_signals`.
"""
head, tail = signals[0], signals[-1]
return dataclasses.replace(
@@ -807,23 +894,38 @@ def combine_export_signals(signals: list[ExportSignalMessage]) -> ExportSignalMe
)
+def final_run_signals(constituents: list[ExportSignalMessage]) -> list[ExportSignalMessage]:
+ """One combined message per run whose last member of the set is its final batch, in load order.
+
+ Each run completes on its own: its post-load, its job status and its cursor promotion happen
+ in the order the runs were loaded, which is the order the loader would have completed them
+ one batch at a time.
+ """
+ members = [CoalesceMember.from_signal(signal) for signal in constituents]
+ finals: list[ExportSignalMessage] = []
+ for run_uuid in runs_in_order(members):
+ run_signals = [signal for signal in constituents if signal.run_uuid == run_uuid]
+ if run_signals[-1].is_final_batch:
+ finals.append(combine_export_signals(run_signals))
+ return finals
+
+
def process_messages(
messages: list[Any],
progress_callback: Callable[[], None] | None = None,
verify_ownership: Callable[[], None] | None = None,
attempt: int = 1,
) -> None:
- """Load consecutive batches of one run into Delta Lake as one write.
+ """Load consecutive batches of one run, or of consecutive runs, into Delta Lake as one write.
Raises ``CoalescingDeclined`` before any side effect when the set cannot be loaded as one
(a constituent already landed, or the batches' schemas do not concatenate); the engine then
loads the constituents one by one.
"""
signals = [ExportSignalMessage.from_dict(message) for message in messages]
- if len({signal.run_uuid for signal in signals}) != 1:
- raise CoalescingDeclined("batches belong to different runs")
- if any(later.batch_index != earlier.batch_index + 1 for earlier, later in zip(signals, signals[1:])):
- raise CoalescingDeclined("batch indexes are not consecutive")
+ violation = set_violation([CoalesceMember.from_signal(signal) for signal in signals])
+ if violation is not None:
+ raise CoalescingDeclined(violation)
combined = combine_export_signals(signals)
with workload_reporting(
@@ -867,12 +969,15 @@ def _process_external_destinations_only(
def _read_constituents(constituents: list[ExportSignalMessage]) -> pa.Table:
- """Read every constituent's parquet file and concatenate them in batch order.
+ """Read every constituent's parquet file and concatenate them in load order.
Batches of one run were converged onto one accumulated schema when they were staged, so they
- normally concatenate as they are; a later batch can still carry a column an earlier one lacked,
- which permissive promotion fills with nulls. Anything that still does not fit declines the set,
- since nothing has been written yet.
+ normally concatenate as they are; a later batch, or a later run, can still carry a column an
+ earlier one lacked, which permissive promotion fills with nulls. Anything that still does not
+ fit declines the set, since nothing has been written yet.
+
+ The order matters: the writer keeps the last row per key, so a later run's row for a key an
+ earlier run also carried is the one that lands.
"""
tables = [read_parquet(signal.s3_path) for signal in constituents]
try:
@@ -889,9 +994,11 @@ def _process_message_reported(
attempt: int = 1,
constituents: list[ExportSignalMessage] | None = None,
) -> None:
- # The batch indexes this write stands for: one for an ordinary batch, every member for a set.
- batch_indexes = (
- [signal.batch_index for signal in constituents] if constituents is not None else [export_signal.batch_index]
+ # The (run, batch index) pairs this write stands for: one for an ordinary batch, every member for a set.
+ members = (
+ [(signal.run_uuid, signal.batch_index) for signal in constituents]
+ if constituents is not None
+ else [(export_signal.run_uuid, export_signal.batch_index)]
)
# Reconnect stale app-DB connections up front so the ORM queries below don't burn all batch attempts.
@@ -912,9 +1019,7 @@ def _process_message_reported(
# delta-history fallback when the Redis dedup flag is missing — the case
# where the writer crashed between `DeltaWriter.write` committing and
# `mark_batch_as_processed` being called.
- job = ExternalDataJob.objects.prefetch_related("schema", "schema__source", "schema__table").get(
- id=export_signal.job_id
- )
+ job = _load_job(export_signal.job_id)
schema = job.schema
if schema is None:
raise ValueError(f"ExternalDataJob {export_signal.job_id} has no schema")
@@ -935,16 +1040,16 @@ def _process_message_reported(
if constituents is not None:
# A set is all-or-nothing: a member that already landed means the others must be checked
# and written one at a time, which the single-batch path knows how to do.
- for index in batch_indexes:
+ for run_uuid, index in members:
if is_batch_already_processed(
export_signal.team_id,
export_signal.schema_id,
- export_signal.run_uuid,
+ run_uuid,
index,
delta_table_ref=delta_table_ref,
is_first_attempt=attempt <= 1,
):
- raise CoalescingDeclined(f"batch {index} was already processed")
+ raise CoalescingDeclined(f"batch {index} of run {run_uuid} was already processed")
already_processed = False
else:
already_processed = is_batch_already_processed(
@@ -1049,7 +1154,11 @@ def _process_message_reported(
"batch_index": str(export_signal.batch_index),
}
if constituents is not None:
- commit_metadata["batch_indexes"] = ",".join(str(index) for index in batch_indexes)
+ commit_metadata["batch_indexes"] = ",".join(
+ str(index) for run_uuid, index in members if run_uuid == export_signal.run_uuid
+ )
+ if any(run_uuid != export_signal.run_uuid for run_uuid, _ in members):
+ commit_metadata["members"] = commit_members_tag(members)
resolution_enabled = cdc_write_mode is not None
@@ -1144,8 +1253,8 @@ def _process_message_reported(
# Marked as soon as the commit lands, before post-load: the final row of a run carries its own
# data now, so a post-load failure must send the retry down the post-load-only path rather
# than through the write again.
- for index in batch_indexes:
- mark_batch_as_processed(export_signal.team_id, export_signal.schema_id, export_signal.run_uuid, index)
+ for run_uuid, index in members:
+ mark_batch_as_processed(export_signal.team_id, export_signal.schema_id, run_uuid, index)
# file_count is the signal that shows a table fragmenting during a long load, so it stays —
# but listing every file costs O(files in table), which is the very thing it measures. Sample
@@ -1169,6 +1278,7 @@ def _process_message_reported(
logger.debug(
"batch_written_to_delta_lake",
batch_index=export_signal.batch_index,
+ batch_count=len(members),
delta_version=delta_table_ref.latest_known_version(delta_table),
file_count=len(delta_table.file_uris()) if sample_file_count else None,
)
@@ -1182,65 +1292,23 @@ def _process_message_reported(
internal_schema=internal_schema,
)
- if export_signal.is_final_batch:
- logger.info(
- "final_batch_received",
- batch_index=export_signal.batch_index,
- total_batches=export_signal.total_batches,
- total_rows=export_signal.total_rows,
- cdc_write_mode=export_signal.cdc_write_mode,
- cdc_table_mode=export_signal.cdc_table_mode,
- sync_type=export_signal.sync_type,
- schema_sync_type=schema.sync_type,
- schema_cdc_table_mode=schema.cdc_table_mode,
- resource_name=export_signal.resource_name,
- )
-
- # Minutes may have passed since the batch's write — re-check before post-load
- # commits and job completion promote the staged cursor under a new owner.
- if verify_ownership is not None:
- verify_ownership()
-
- report_phase("post_load")
- prepared_queryable_folder = async_to_sync(run_post_load_operations)(
- job=job,
- schema=schema,
- source=schema.source,
+ # Every run whose final batch landed in this write completes now, in load order.
+ if constituents is not None:
+ finals = final_run_signals(constituents)
+ else:
+ finals = [export_signal] if export_signal.is_final_batch else []
+ for run_signal in finals:
+ run_job = job if run_signal.job_id == export_signal.job_id else _load_job(run_signal.job_id)
+ run_schema = run_job.schema
+ if run_schema is None:
+ raise ValueError(f"ExternalDataJob {run_signal.job_id} has no schema")
+ _finalize_run(
+ run_signal,
+ job=run_job,
+ schema=run_schema,
delta_table_ref=delta_table_ref,
- row_count=export_signal.total_rows or 0,
- table_schema_dict=internal_schema.to_hogql_types(),
- resource_name=export_signal.resource_name,
- logger=logger,
- cdc_write_mode=export_signal.cdc_write_mode,
- )
-
- # Post-load can run minutes (compaction, S3 prep) — re-check before
- # completion promotes the cursor and releases the lock under a new owner.
- if verify_ownership is not None:
- verify_ownership()
-
- report_phase("finalize")
- _mark_job_completed(export_signal)
-
- if prepared_queryable_folder:
- _trigger_ducklake_register_data_imports(export_signal, prepared_queryable_folder)
-
- _trigger_post_import_workflow(export_signal)
-
- logger.debug("post_load_operations_complete")
-
- posthoganalytics.capture(
- distinct_id=get_machine_id(),
- event="warehouse_v3_load_completed",
- properties={
- "team_id": export_signal.team_id,
- "schema_id": export_signal.schema_id,
- "source_id": export_signal.source_id,
- "resource_name": export_signal.resource_name,
- "sync_type": export_signal.sync_type,
- "total_batches": export_signal.total_batches,
- "total_rows": export_signal.total_rows,
- },
+ internal_schema=internal_schema,
+ verify_ownership=verify_ownership,
)
except OwnershipLostError:
# Benign fencing abandon: the engine re-raises this without writing a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index 2abbe8a3577f..e07de36853be 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -1,4 +1,7 @@
import tempfile
+from collections.abc import Iterator
+from contextlib import ExitStack, contextmanager
+from pathlib import Path
from typing import Any
import pytest
@@ -17,6 +20,10 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
TOAST_OMITTED_COLUMN,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (
+ make_local_table_ref,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import commit_covers_batch
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
CoalescingDeclined,
)
@@ -732,16 +739,189 @@ class TestProcessMessages:
@parameterized.expand(
[
- ("different_runs", [{"batch_index": 0}, {"batch_index": 1, "run_uuid": "run-2"}]),
("gap_in_indexes", [{"batch_index": 0}, {"batch_index": 2}]),
+ ("fresh_run_batch_zero", [{"batch_index": 3}, {"batch_index": 0, "run_uuid": "run-2"}]),
+ (
+ "full_refresh_across_runs",
+ [
+ {"batch_index": 3, "sync_type": "full_refresh"},
+ {"batch_index": 0, "run_uuid": "run-2", "is_resume": True, "sync_type": "full_refresh"},
+ ],
+ ),
+ (
+ "other_primary_keys",
+ [{"batch_index": 3}, {"batch_index": 0, "run_uuid": "run-2", "is_resume": True, "primary_keys": ["k"]}],
+ ),
+ (
+ "run_reappears",
+ [{"batch_index": 3}, {"batch_index": 0, "run_uuid": "run-2", "is_resume": True}, {"batch_index": 4}],
+ ),
+ ("cdc", [{"batch_index": 0, "sync_type": "cdc"}, {"batch_index": 1, "sync_type": "cdc"}]),
]
)
- def test_a_set_that_is_not_one_consecutive_run_is_declined(
+ def test_a_set_the_rules_reject_is_declined_before_any_side_effect(
self, _case: str, overrides: list[dict[str, Any]]
) -> None:
+ # The consumer never builds these, so reaching here means a planner bug; the sink must
+ # refuse rather than merge rows the serial loader would have written differently.
with pytest.raises(CoalescingDeclined):
process_messages([_message(**o) for o in overrides])
+ @parameterized.expand(
+ [
+ # Both runs end in the set: each completes, in load order, with its own job and totals.
+ ("both_runs_final", True, ["run-1", "run-2"], ["job-1", "job-2"]),
+ # The second run continues past the set: only the first run completes.
+ ("second_run_open", False, ["run-1"], ["job-1"]),
+ ]
+ )
+ @patch(f"{_PROCESSOR}.posthoganalytics")
+ @patch(f"{_PROCESSOR}.mark_batch_as_processed")
+ @patch(f"{_PROCESSOR}._trigger_post_import_workflow")
+ @patch(f"{_PROCESSOR}._trigger_ducklake_register_data_imports")
+ @patch(f"{_PROCESSOR}._mark_job_completed")
+ @patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value="folder")
+ @patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))
+ @patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)
+ @patch(f"{_PROCESSOR}.DeltaWriter")
+ @patch(f"{_PROCESSOR}.DeltaTableRef")
+ @patch(f"{_PROCESSOR}.ExternalDataJob")
+ def test_a_set_spanning_runs_keeps_every_member_and_every_run_apart(
+ self,
+ _case: str,
+ second_run_final: bool,
+ completed_runs: list[str],
+ completed_jobs: list[str],
+ mock_job_model: MagicMock,
+ mock_helper_cls: MagicMock,
+ mock_writer_cls: MagicMock,
+ mock_already: MagicMock,
+ _read: MagicMock,
+ mock_post_load: AsyncMock,
+ mock_mark_completed: MagicMock,
+ _ducklake: MagicMock,
+ mock_trigger: MagicMock,
+ mock_mark_processed: MagicMock,
+ _analytics: MagicMock,
+ ) -> None:
+ jobs = {job_id: MagicMock(name=job_id) for job_id in ("job-1", "job-2")}
+ mock_job_model.objects.prefetch_related.return_value.get.side_effect = lambda id: jobs[id]
+ delta_table = MagicMock()
+ delta_table.schema.return_value = pa.schema([pa.field("id", pa.int64())])
+ delta_table.file_uris.return_value = []
+ mock_helper_cls.return_value.get_delta_table = AsyncMock(return_value=None)
+ mock_writer_cls.return_value.write = AsyncMock(return_value=delta_table)
+
+ messages = _run_messages("run-1", start=3, count=2, final=True) + _run_messages(
+ "run-2", start=0, count=2, final=second_run_final, is_resume=True
+ )
+ process_messages(messages)
+
+ members = [("run-1", 3), ("run-1", 4), ("run-2", 0), ("run-2", 1)]
+ assert [(call.args[2], call.args[3]) for call in mock_already.call_args_list] == members
+ assert [(call.args[2], call.args[3]) for call in mock_mark_processed.call_args_list] == members
+ write = mock_writer_cls.return_value.write
+ write.assert_awaited_once()
+ assert write.await_args.kwargs["data"].num_rows == 4
+ assert write.await_args.kwargs["should_overwrite_table"] is False
+ assert write.await_args.kwargs["commit_metadata"] == {
+ "run_uuid": "run-1",
+ "batch_index": "3",
+ "batch_indexes": "3,4",
+ "members": "run-1:3,run-1:4,run-2:0,run-2:1",
+ }
+ assert [call.kwargs["job"] for call in mock_post_load.await_args_list] == [jobs[j] for j in completed_jobs]
+ assert [call.kwargs["row_count"] for call in mock_post_load.await_args_list] == [
+ _run_total_rows(run) for run in completed_runs
+ ]
+ assert [call.args[0].run_uuid for call in mock_mark_completed.call_args_list] == completed_runs
+ assert [call.args[0].job_id for call in mock_mark_completed.call_args_list] == completed_jobs
+ assert [call.args[0].run_uuid for call in mock_trigger.call_args_list] == completed_runs
+
+
+def _run_total_rows(run_uuid: str) -> int:
+ return 1000 + int(run_uuid[-1])
+
+
+def _run_messages(
+ run_uuid: str, *, start: int, count: int, final: bool, is_resume: bool = False, **overrides: Any
+) -> list[dict[str, Any]]:
+ return [
+ _message(
+ **{
+ "run_uuid": run_uuid,
+ "job_id": f"job-{run_uuid[-1]}",
+ "batch_index": start + offset,
+ "s3_path": f"s3://bucket/{run_uuid}/{start + offset}.parquet",
+ "is_resume": is_resume,
+ "is_final_batch": final and offset == count - 1,
+ "total_batches": start + count if final and offset == count - 1 else None,
+ "total_rows": _run_total_rows(run_uuid) if final and offset == count - 1 else None,
+ **overrides,
+ }
+ )
+ for offset in range(count)
+ ]
+
+
+class TestCrossRunKeyResolution:
+ """Two runs of one set carrying the same primary key: the later run's row must be the one in the
+ table, exactly as when the loader takes the runs one batch at a time. deltalite refuses a source
+ batch with a repeated key, so the writer's keep-last deduplication over the concatenated set is
+ what makes the write both possible and correct."""
+
+ _SEED = pa.table({"id": [1, 2], "name": ["seed_1", "seed_2"]})
+ _BATCHES = {
+ "s3://bucket/run-1/3.parquet": pa.table({"id": [1, 3], "name": ["from_run_1", "new_3"]}),
+ "s3://bucket/run-2/0.parquet": pa.table({"id": [1, 4], "name": ["from_run_2", "new_4"]}),
+ }
+
+ @contextmanager
+ def _real_local_table(self, table_path: str) -> Iterator[None]:
+ with ExitStack() as stack:
+ stack.enter_context(patch(f"{_PROCESSOR}.posthoganalytics"))
+ stack.enter_context(patch(f"{_PROCESSOR}.mark_batch_as_processed"))
+ stack.enter_context(patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False))
+ stack.enter_context(patch(f"{_PROCESSOR}.read_parquet", side_effect=lambda path: self._BATCHES[path]))
+ stack.enter_context(
+ patch(f"{_PROCESSOR}.DeltaTableRef", side_effect=lambda **kwargs: make_local_table_ref(table_path))
+ )
+ job_model = stack.enter_context(patch(f"{_PROCESSOR}.ExternalDataJob"))
+ job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()
+ yield
+
+ def _messages(self) -> list[dict[str, Any]]:
+ return _run_messages("run-1", start=3, count=1, final=False) + _run_messages(
+ "run-2", start=0, count=1, final=False, is_resume=True
+ )
+
+ def test_the_later_run_wins_a_key_both_runs_carry(self, tmp_path: Path) -> None:
+ coalesced_path = str(tmp_path / "coalesced")
+ serial_path = str(tmp_path / "serial")
+ write_deltalake(coalesced_path, self._SEED)
+ write_deltalake(serial_path, self._SEED)
+
+ with self._real_local_table(coalesced_path):
+ process_messages(self._messages())
+ with self._real_local_table(serial_path):
+ for message in self._messages():
+ process_message(message)
+
+ coalesced = DeltaTable(coalesced_path)
+ rows = coalesced.to_pyarrow_table().sort_by("id")
+ assert rows.column("id").to_pylist() == [1, 2, 3, 4]
+ assert rows.column("name").to_pylist() == ["from_run_2", "seed_2", "new_3", "new_4"]
+ assert rows.to_pydict() == DeltaTable(serial_path).to_pyarrow_table().sort_by("id").to_pydict()
+
+ # One deltalite commit for the set (a MERGE would mean the delta-rs fallback wrote it), and
+ # every member of every run is found in it.
+ data_commits = [commit for commit in coalesced.history() if commit["operation"] != "SET TBLPROPERTIES"]
+ assert [commit["operation"] for commit in data_commits] == ["WRITE", "WRITE"]
+ set_commit = data_commits[0]
+ assert commit_covers_batch(set_commit, "run-1", 3)
+ assert commit_covers_batch(set_commit, "run-2", 0)
+ assert not commit_covers_batch(set_commit, "run-2", 1)
+
class TestPostImportTrigger:
"""The V3 hand-off to `data-import-post-import`: without it the load-dependent
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 5d6907ce1218..a5afb80f24ab 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
@@ -50,6 +50,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_group_by_key,
_is_transient_queue_db_error,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.coalescing import (
+ CoalesceCaps,
+ CoalesceMember,
+ extends_set,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
_UNSET,
@@ -180,41 +185,9 @@ JOB_STATUS_CACHE_TTL_SECONDS = 30
JOB_STATUS_CACHE_MAX_ENTRIES = 1000
-# Bounds on a set of consecutive batches loaded as one Delta commit. A batch is at most one
-# extraction chunk (500k rows, 200 MiB of Arrow), so the row cap keeps a set to what one large
-# batch already costs, and the byte cap (parquet on disk, several times smaller than the Arrow it
-# decodes to) keeps many small batches from adding up past it.
-COALESCE_MAX_BATCHES = 8
-COALESCE_MAX_ROWS = 500_000
-COALESCE_MAX_BYTES = 64 * 1024 * 1024
-# CDC batches resolve positions against the table between writes, and a batch bound for external
-# destinations is delivered per batch, so neither is folded into a set.
-COALESCABLE_SYNC_TYPES: frozenset[str] = frozenset({"incremental", "append", "full_refresh"})
-
-
-def _coalescable(batch: PendingBatch) -> bool:
- return (
- batch.sync_type in COALESCABLE_SYNC_TYPES
- # A redelivery may sit on a half-finished write; its idempotency check runs per batch.
- and batch.latest_attempt == 0
- and not batch.destination_ids
- and batch.metadata.get("cdc_write_mode") is None
- )
-
-
-def _extends_coalesced_set(current: list[PendingBatch], batch: PendingBatch) -> bool:
- head = current[-1]
- if not (_coalescable(head) and _coalescable(batch)):
- return False
- if batch.run_uuid != head.run_uuid or batch.job_id != head.job_id:
- return False
- if batch.batch_index != head.batch_index + 1:
- return False
- if len(current) >= COALESCE_MAX_BATCHES:
- return False
- rows = sum(member.row_count for member in current) + batch.row_count
- size = sum(member.byte_size for member in current) + batch.byte_size
- return rows <= COALESCE_MAX_ROWS and size <= COALESCE_MAX_BYTES
+def _first_delivery(batch: PendingBatch) -> bool:
+ # A redelivery may sit on a half-finished write; its idempotency check runs per batch.
+ return batch.latest_attempt == 0
def _is_transient_queue_connection_drop(err: Exception, conn: psycopg.AsyncConnection[Any]) -> bool:
@@ -954,15 +927,30 @@ class DeltaBatchConsumerAdapter:
return None
def coalesce_group(self, batches: list[PendingBatch]) -> list[list[PendingBatch]]:
+ """Cut the claimed batches of one group into the sets the sink loads as one write.
+
+ Only adjacent batches join, so every set keeps the claim order: the order the loader would
+ have taken the batches in one at a time.
+ """
+ caps = CoalesceCaps.from_settings()
sets: list[list[PendingBatch]] = []
current: list[PendingBatch] = []
+ current_members: list[CoalesceMember] = []
for batch in batches:
- if current and _extends_coalesced_set(current, batch):
+ member = CoalesceMember.from_batch(batch)
+ if (
+ current
+ and _first_delivery(current[-1])
+ and _first_delivery(batch)
+ and extends_set(current_members, member, caps)
+ ):
current.append(batch)
+ current_members.append(member)
continue
if current:
sets.append(current)
current = [batch]
+ current_members = [member]
if current:
sets.append(current)
return sets
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
index bab1653018a4..1e528a12025c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
@@ -264,13 +264,35 @@ class ConsumerMetrics:
active_groups: Gauge
recovery_sweeps_total: Counter
coalesced_sets_total: Counter
+ coalesced_set_batches: Histogram
+ coalesced_set_runs: Histogram
+ coalesced_set_rows: Histogram
+COALESCED_SET_BATCHES_BUCKETS = (1, 2, 4, 8, 16, 32, 64, 128, 256)
+COALESCED_SET_RUNS_BUCKETS = (1, 2, 3, 4, 6, 8, 12, 16)
+COALESCED_SET_ROWS_BUCKETS = (100, 1_000, 10_000, 50_000, 100_000, 250_000, 500_000, 1_000_000)
+
COALESCED_SETS_TOTAL = Counter(
"warehouse_pg_consumer_coalesced_sets_total",
- "Sets of consecutive batches of one run loaded as a single write, by outcome",
+ "Sets of consecutive batches loaded as a single write, by outcome",
labelnames=["outcome"],
)
+COALESCED_SET_BATCHES = Histogram(
+ "warehouse_pg_consumer_coalesced_set_batches",
+ "Batches per set loaded as a single write",
+ buckets=COALESCED_SET_BATCHES_BUCKETS,
+)
+COALESCED_SET_RUNS = Histogram(
+ "warehouse_pg_consumer_coalesced_set_runs",
+ "Runs per set loaded as a single write",
+ buckets=COALESCED_SET_RUNS_BUCKETS,
+)
+COALESCED_SET_ROWS = Histogram(
+ "warehouse_pg_consumer_coalesced_set_rows",
+ "Rows per set loaded as a single write",
+ buckets=COALESCED_SET_ROWS_BUCKETS,
+)
DELTA_CONSUMER_METRICS = ConsumerMetrics(
batches_processed_total=BATCHES_PROCESSED_TOTAL,
@@ -283,6 +305,9 @@ DELTA_CONSUMER_METRICS = ConsumerMetrics(
active_groups=ACTIVE_GROUPS,
recovery_sweeps_total=RECOVERY_SWEEPS_TOTAL,
coalesced_sets_total=COALESCED_SETS_TOTAL,
+ coalesced_set_batches=COALESCED_SET_BATCHES,
+ coalesced_set_runs=COALESCED_SET_RUNS,
+ coalesced_set_rows=COALESCED_SET_ROWS,
)
_metrics_by_prefix: dict[str, ConsumerMetrics] = {}
@@ -342,9 +367,24 @@ def make_consumer_metrics(prefix: str) -> ConsumerMetrics:
),
coalesced_sets_total=Counter(
f"{p}_coalesced_sets_total",
- "Sets of consecutive batches of one run loaded as a single write, by outcome",
+ "Sets of consecutive batches loaded as a single write, by outcome",
labelnames=["outcome"],
),
+ coalesced_set_batches=Histogram(
+ f"{p}_coalesced_set_batches",
+ "Batches per set loaded as a single write",
+ buckets=COALESCED_SET_BATCHES_BUCKETS,
+ ),
+ coalesced_set_runs=Histogram(
+ f"{p}_coalesced_set_runs",
+ "Runs per set loaded as a single write",
+ buckets=COALESCED_SET_RUNS_BUCKETS,
+ ),
+ coalesced_set_rows=Histogram(
+ f"{p}_coalesced_set_rows",
+ "Rows per set loaded as a single write",
+ buckets=COALESCED_SET_ROWS_BUCKETS,
+ ),
)
_metrics_by_prefix[prefix] = metrics
return metrics
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index 0ff9676d01a3..725c55ce02c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -6,6 +6,7 @@ import pytest
from unittest.mock import AsyncMock, patch
from django.db import OperationalError as DjangoOperationalError
+from django.test import override_settings
import psycopg
import structlog
@@ -3692,11 +3693,14 @@ class TestIsRetryableError:
def _run_batches(count: int, *, run_uuid: str = "run-1", start: int = 0, **overrides: Any) -> list[PendingBatch]:
return [
_make_batch(
- id=f"00000000-0000-0000-0000-{run_uuid[-1]}{start + offset:011d}",
- run_uuid=run_uuid,
- batch_index=start + offset,
- sync_type="incremental",
- **overrides,
+ **{
+ "id": f"00000000-0000-0000-0000-{run_uuid[-1]}{start + offset:011d}",
+ "job_id": f"job-{run_uuid[-1]}",
+ "run_uuid": run_uuid,
+ "batch_index": start + offset,
+ "sync_type": "incremental",
+ **overrides,
+ }
)
for offset in range(count)
]
@@ -3716,9 +3720,63 @@ class TestCoalesceGroup:
batches = _run_batches(2) + _run_batches(1, start=3)
assert self._sets(batches) == [[0, 1], [3]]
- def test_a_set_never_crosses_a_run(self):
- batches = _run_batches(2, run_uuid="run-1") + _run_batches(2, run_uuid="run-2")
- assert self._sets(batches) == [[0, 1], [0, 1]]
+ @pytest.mark.parametrize(
+ "second_run,expected",
+ [
+ # A resume attempt continues the same load, so its rows follow the first run's in one write.
+ ({"is_resume": True}, [[0, 1, 0, 1]]),
+ ({"is_resume": True, "start": 7}, [[0, 1, 7, 8]]),
+ ({"is_resume": True, "sync_type": "append"}, [[0, 1, 0, 1]]),
+ # Batch 0 of a fresh run may overwrite the table, so it heads its own write.
+ ({}, [[0, 1], [0, 1]]),
+ # A full refresh replaces the table run by run.
+ ({"is_resume": True, "sync_type": "full_refresh"}, [[0, 1], [0, 1]]),
+ # Rows merged under the head's keys or partitioning would land wrong for a run configured differently.
+ ({"is_resume": True, "metadata": {"primary_keys": ["other"]}}, [[0, 1], [0, 1]]),
+ ({"is_resume": True, "metadata": {"partition_keys": ["id"], "partition_count": 4}}, [[0, 1], [0, 1]]),
+ # The writer takes the head's first-sync flag, which decides between an append and a merge.
+ ({"is_resume": True, "is_first_ever_sync": True}, [[0, 1], [0, 1]]),
+ ],
+ ids=[
+ "resume_joins",
+ "resume_from_later_index_joins",
+ "append_joins",
+ "fresh_batch_zero_splits",
+ "full_refresh_splits",
+ "other_primary_keys_split",
+ "other_partitioning_splits",
+ "first_sync_flag_splits",
+ ],
+ )
+ @override_settings(DATA_WAREHOUSE_V3_COALESCE_ACROSS_RUNS=True)
+ def test_consecutive_runs(self, second_run: dict[str, Any], expected: list[list[int]]):
+ first_sync_type = second_run.get("sync_type", "incremental")
+ batches = _run_batches(2, run_uuid="run-1", sync_type=first_sync_type) + _run_batches(
+ 2, run_uuid="run-2", **second_run
+ )
+ assert self._sets(batches) == expected
+
+ def test_cross_run_sets_can_be_switched_off(self):
+ batches = _run_batches(2, run_uuid="run-1") + _run_batches(2, run_uuid="run-2", is_resume=True)
+ with override_settings(DATA_WAREHOUSE_V3_COALESCE_ACROSS_RUNS=False):
+ assert self._sets(batches) == [[0, 1], [0, 1]]
+
+ @override_settings(DATA_WAREHOUSE_V3_COALESCE_ACROSS_RUNS=True)
+ def test_members_keep_the_claim_order_and_a_run_never_reappears_in_a_set(self):
+ # The claim query orders a group by (created_at, batch_index) and the loader takes that order
+ # one batch at a time; a set that reordered members, or folded a run back in after another
+ # run, would merge rows in an order the serial loader never produced.
+ batches = (
+ _run_batches(2, run_uuid="run-1", start=5)
+ + _run_batches(1, run_uuid="run-2", is_resume=True)
+ + _run_batches(1, run_uuid="run-1", start=7)
+ )
+ sets = DeltaBatchConsumerAdapter().coalesce_group(batches)
+ assert [batch.id for batch_set in sets for batch in batch_set] == [batch.id for batch in batches]
+ assert [[(b.run_uuid, b.batch_index) for b in s] for s in sets] == [
+ [("run-1", 5), ("run-1", 6), ("run-2", 0)],
+ [("run-1", 7)],
+ ]
def test_a_final_only_marker_row_stays_alone(self):
# An older producer repeats the last batch's index as a final-only row; it is not a new batch.
@@ -3755,16 +3813,23 @@ class TestCoalesceGroup:
assert self._sets(batches) == [[0], [1], [2]]
@pytest.mark.parametrize(
- "count,overrides,expected",
+ "count,overrides,settings_overrides,expected",
[
- (3, {"row_count": 300_000, "byte_size": 1}, [[0], [1], [2]]),
- (3, {"row_count": 1, "byte_size": 40 * 1024 * 1024}, [[0], [1], [2]]),
- (9, {"row_count": 1, "byte_size": 1}, [list(range(8)), [8]]),
+ (3, {"row_count": 300_000, "byte_size": 1}, {}, [[0], [1], [2]]),
+ (3, {"row_count": 1, "byte_size": 40 * 1024 * 1024}, {}, [[0], [1], [2]]),
+ # The row cap binds long before the count backstop for batches of ordinary size.
+ (60, {"row_count": 10_000, "byte_size": 1}, {}, [list(range(50)), list(range(50, 60))]),
+ (9, {"row_count": 1, "byte_size": 1}, {"DATA_WAREHOUSE_V3_COALESCE_MAX_BATCHES": 8}, [list(range(8)), [8]]),
+ (3, {"row_count": 10, "byte_size": 1}, {"DATA_WAREHOUSE_V3_COALESCE_MAX_ROWS": 20}, [[0, 1], [2]]),
+ (3, {"row_count": 1, "byte_size": 10}, {"DATA_WAREHOUSE_V3_COALESCE_MAX_BYTES": 20}, [[0, 1], [2]]),
],
- ids=["rows", "bytes", "count"],
+ ids=["rows", "bytes", "rows_bind_before_count", "count_setting", "rows_setting", "bytes_setting"],
)
- def test_sets_are_capped(self, count: int, overrides: dict[str, Any], expected: list[list[int]]):
- assert self._sets(_run_batches(count, **overrides)) == expected
+ def test_sets_are_capped(
+ self, count: int, overrides: dict[str, Any], settings_overrides: dict[str, Any], expected: list[list[int]]
+ ):
+ with override_settings(**settings_overrides):
+ assert self._sets(_run_batches(count, **overrides)) == expected
class _BatchStatus(NamedTuple):
@@ -3831,21 +3896,23 @@ class TestProcessGroupCoalescing:
ids=["declined", "failed"],
)
@pytest.mark.asyncio
+ @override_settings(DATA_WAREHOUSE_V3_COALESCE_ACROSS_RUNS=True)
async def test_a_set_that_cannot_load_falls_back_to_its_members(
self, error: Exception, expected_latest_attempt: int, expected_status_attempt: int
):
process_batches = AsyncMock(side_effect=error)
- seen: list[tuple[int, int]] = []
+ seen: list[tuple[str, int, int]] = []
async def process_batch(batch, verify_ownership=None):
- seen.append((batch.batch_index, batch.latest_attempt))
+ seen.append((batch.run_uuid, batch.batch_index, batch.latest_attempt))
consumer = self._consumer(process_batches, process_batch)
- batches = _run_batches(2)
+ # A set that spans runs falls back run by run, each member under its own identity.
+ batches = _run_batches(1, run_uuid="run-1", start=4) + _run_batches(1, run_uuid="run-2", is_resume=True)
statuses = await self._run_group(consumer, batches)
- assert seen == [(0, expected_latest_attempt), (1, expected_latest_attempt)]
+ assert seen == [("run-1", 4, expected_latest_attempt), ("run-2", 0, expected_latest_attempt)]
# The set's own executing rows come first; each member then goes through the single-batch
# transitions, at the same attempt when nothing was written and at the next one otherwise.
assert statuses == [