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): stop the v3 load consumer paying per batch for table size (#92919)

Tom Owersd6e602941588
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py
index 5d319d0894f5..afdb3396a44e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/idempotency.py
@@ -65,6 +65,8 @@ def is_batch_already_processed(
batch_index: int,
delta_table_ref: DeltaTableRef | None = None,
destination_id: str | None = None,
+ *,
+ is_first_attempt: bool = False,
) -> bool:
"""Check if a batch has already been processed.
@@ -77,12 +79,21 @@ def is_batch_already_processed(
between `DeltaWriter.write` committing and `mark_batch_as_processed` running —
on Kafka redelivery we'd otherwise re-write the same batch and produce
duplicate rows.
+
+ `is_first_attempt` skips that slow path. A batch that has never been delivered has
+ no earlier write to find, so the scan can only answer "no" — and it is not cheap:
+ it opens the table and reads the last 50 commits, both of which grow with the
+ table's file count, so a long first sync pays more for it on every batch. The skip
+ applies only when Redis answered: a Redis outage leaves the fast path inconclusive,
+ and the scan is then the only protection against a duplicate write.
"""
with get_redis_client() as redis_client:
if redis_client is not None:
key = get_idempotency_key(team_id, schema_id, run_uuid, batch_index, destination_id)
if redis_client.exists(key) == 1:
return True
+ if is_first_attempt:
+ return False
if delta_table_ref is None:
return False
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 842e322a3937..3b7eefbf5b0a 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
@@ -94,6 +94,11 @@ from products.warehouse_sources.backend.temporal.data_imports.workload_report im
logger = structlog.get_logger(__name__)
+# Batch interval at which `batch_written_to_delta_lake` carries a file count. Frequent enough to
+# show a table fragmenting over a multi-hundred-batch load, rare enough that the listing it needs
+# stays off the per-batch path.
+FILE_COUNT_LOG_SAMPLE_EVERY = 100
+
def _get_write_type(sync_type: SyncTypeLiteral) -> Literal["incremental", "full_refresh", "append"]:
"""Convert sync type to write type for DeltaTableRef."""
@@ -323,6 +328,15 @@ def _apply_partitioning(
return pa_table
+def _partial_data_loading_applies(export_signal: ExportSignalMessage, schema: ExternalDataSchema) -> bool:
+ """Whether this batch feeds partial data loading (first-ever sync, Stripe only).
+
+ Read before the write as well as after: `previous_file_uris` only exists to serve this
+ feature, and collecting it means listing every file in the table.
+ """
+ return export_signal.is_first_ever_sync and supports_partial_data_loading(schema)
+
+
async def _handle_partial_data_loading(
export_signal: ExportSignalMessage,
job: ExternalDataJob,
@@ -332,10 +346,7 @@ async def _handle_partial_data_loading(
internal_schema: HogQLSchema,
) -> None:
"""Make data available for querying during first-ever sync for Stripe sources."""
- if not export_signal.is_first_ever_sync:
- return
-
- if not supports_partial_data_loading(schema):
+ if not _partial_data_loading_applies(export_signal, schema):
return
current_file_uris = delta_table.file_uris()
@@ -736,9 +747,14 @@ def process_message(
message: Any,
progress_callback: Callable[[], None] | None = None,
verify_ownership: Callable[[], None] | None = None,
+ attempt: int = 1,
) -> None:
"""Load one batch into Delta Lake. ``verify_ownership`` raises if the group lease was lost;
- re-checked before each lasting side effect since the heartbeat only detects loss between beats."""
+ re-checked before each lasting side effect since the heartbeat only detects loss between beats.
+
+ ``attempt`` is this batch's delivery number, counting from 1. It selects how hard the
+ idempotency check works: only a redelivery can have a half-finished predecessor to detect.
+ """
export_signal = ExportSignalMessage.from_dict(message)
# The consumer is where v3 merges — the memory-heavy phase — actually run, so it must self-report
@@ -751,7 +767,7 @@ def process_message(
host=socket.gethostname(),
initial_phase="load",
):
- _process_message_reported(message, export_signal, progress_callback, verify_ownership)
+ _process_message_reported(message, export_signal, progress_callback, verify_ownership, attempt)
def _process_external_destinations_only(
@@ -785,6 +801,7 @@ def _process_message_reported(
export_signal: "ExportSignalMessage",
progress_callback: Callable[[], None] | None,
verify_ownership: Callable[[], None] | None,
+ attempt: int = 1,
) -> None:
# Reconnect stale app-DB connections up front so the ORM queries below don't burn all batch attempts.
close_old_connections()
@@ -834,6 +851,7 @@ def _process_message_reported(
export_signal.run_uuid,
export_signal.batch_index,
delta_table_ref=delta_table_ref,
+ is_first_attempt=attempt <= 1,
)
# The warehouse having this batch says nothing about the other destinations, so
@@ -902,8 +920,14 @@ def _process_message_reported(
pa_table = _apply_partitioning(export_signal, pa_table, existing_delta_table, schema)
- # Capture file URIs before write for partial data loading
- previous_file_uris = existing_delta_table.file_uris() if existing_delta_table else []
+ # Capture file URIs before write for partial data loading. The listing is O(files in
+ # table), so skip it entirely when no consumer wants it — during a long first sync the
+ # table can hold millions of files and every batch would pay to build a list nothing reads.
+ previous_file_uris = (
+ existing_delta_table.file_uris()
+ if existing_delta_table is not None and _partial_data_loading_applies(export_signal, schema)
+ else []
+ )
primary_keys = export_signal.primary_keys
cdc_write_mode = export_signal.cdc_write_mode
@@ -1025,10 +1049,15 @@ def _process_message_reported(
internal_schema.add_pyarrow_schema(pyarrow_schema_from_arrow_exportable(delta_table.schema()))
internal_schema.add_pyarrow_table(pa_table)
+ # 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
+ # it instead: the trend is what matters, and the version is cheap enough to log every batch.
+ sample_file_count = export_signal.batch_index % FILE_COUNT_LOG_SAMPLE_EVERY == 0
logger.debug(
"batch_written_to_delta_lake",
batch_index=export_signal.batch_index,
- file_count=len(delta_table.file_uris()),
+ delta_version=delta_table.version(),
+ file_count=len(delta_table.file_uris()) if sample_file_count else None,
)
async_to_sync(_handle_partial_data_loading)(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_idempotency.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_idempotency.py
index 5ee0d3340cf0..737d84f74347 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_idempotency.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_idempotency.py
@@ -62,14 +62,23 @@ class TestIsBatchAlreadyProcessed:
@parameterized.expand(
[
- # (name, redis_exists, helper_state, expected_result)
- ("redis_hit_no_helper", 1, None, True),
- ("redis_hit_short_circuits_helper", 1, False, True),
- ("redis_miss_no_helper", 0, None, False),
- ("redis_miss_helper_hit", 0, True, True),
- ("redis_miss_helper_miss", 0, False, False),
- ("redis_unavailable_no_helper", None, None, False),
- ("redis_unavailable_helper_hit", None, True, True),
+ # (name, redis_exists, helper_state, is_first_attempt, expected_result)
+ ("redis_hit_no_helper", 1, None, False, True),
+ ("redis_hit_short_circuits_helper", 1, False, False, True),
+ ("redis_miss_no_helper", 0, None, False, False),
+ ("redis_miss_helper_hit", 0, True, False, True),
+ ("redis_miss_helper_miss", 0, False, False, False),
+ ("redis_unavailable_no_helper", None, None, False, False),
+ ("redis_unavailable_helper_hit", None, True, False, True),
+ # A first delivery has no half-finished predecessor, so the scan is skipped even
+ # though the helper would have reported a commit. Contrast redis_miss_helper_hit.
+ ("first_attempt_skips_helper", 0, True, True, False),
+ # The Redis flag still wins on a first attempt — a batch redelivered after its
+ # flag was written must not be loaded twice.
+ ("first_attempt_redis_hit", 1, None, True, True),
+ # Redis down leaves the fast path inconclusive, so the scan is the only check
+ # left and must run whatever the attempt number says.
+ ("first_attempt_redis_unavailable_still_scans", None, True, True, True),
]
)
def test_decision_matrix(
@@ -77,6 +86,7 @@ class TestIsBatchAlreadyProcessed:
_name: str,
redis_exists: int | None,
helper_state: bool | None,
+ is_first_attempt: bool,
expected_result: bool,
):
client = _redis_client(redis_exists)
@@ -90,6 +100,7 @@ class TestIsBatchAlreadyProcessed:
run_uuid="r",
batch_index=0,
delta_table_ref=helper,
+ is_first_attempt=is_first_attempt,
)
assert result is expected_result
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
index 8e39314ec8d8..cb2bb74a8a39 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
@@ -29,6 +29,8 @@ async def process_batch(batch: PendingBatch, verify_ownership: Callable[[], None
"""Load a single batch into Delta Lake, reusing the existing processor."""
# thread_sensitive=False: the default single-thread executor would cap the pod's
# real parallelism at 1; process_message is self-contained, so cross-thread is safe.
+ # `latest_attempt` counts attempts already recorded, so the delivery starting now is the next
+ # one — same arithmetic the consumer uses when it stamps the status row.
await sync_to_async(process_message, thread_sensitive=False)(
- batch.to_export_signal(), verify_ownership=verify_ownership
+ batch.to_export_signal(), verify_ownership=verify_ownership, attempt=batch.latest_attempt + 1
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_load.py
new file mode 100644
index 000000000000..7d935f28bd70
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_load.py
@@ -0,0 +1,60 @@
+from typing import Any
+
+import pytest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ PendingBatch,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load import (
+ process_batch,
+)
+
+_LOAD_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load"
+
+
+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)
+
+
+class TestProcessBatch:
+ @parameterized.expand(
+ [
+ ("never_delivered", 0, 1),
+ ("one_prior_attempt", 1, 2),
+ ("several_prior_attempts", 4, 5),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_forwards_attempt_number(self, _name: str, latest_attempt: int, expected_attempt: int):
+ # An off-by-one here reads a redelivery as a first delivery, which lets the processor skip
+ # the delta-history idempotency scan and re-write a batch a crashed attempt already committed.
+ with patch(f"{_LOAD_MODULE}.process_message") as mock_process_message:
+ await process_batch(_make_batch(latest_attempt=latest_attempt))
+
+ assert mock_process_message.call_args.kwargs["attempt"] == expected_attempt
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index ea86a8f0ee63..1ebd86605ad5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -212,7 +212,13 @@ class _PostgresQueueReplay:
batch_index: int,
delta_table_ref: Any = None,
destination_id: str | None = None,
+ *,
+ is_first_attempt: bool = False,
) -> bool:
+ # `is_first_attempt` is accepted for signature-compatibility with the real
+ # `is_batch_already_processed` (which callers invoke with it as a keyword),
+ # but this in-memory replay tracks "already processed" purely by which keys
+ # it has already seen, so it doesn't need to branch on it.
# Keyed by destination as well, mirroring the real check: a batch the warehouse has
# taken is not yet done for a destination that has not.
key = (run_uuid, batch_index, destination_id)