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.

feat(data-imports): skip no-op delta maintenance and publish on zero-row syncs (#84863)

Daniel RCed656534befe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
index 6bf1bb240181..4cd5d6696a1d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py
@@ -1,3 +1,4 @@
+import datetime as dt
from typing import TYPE_CHECKING, Any, Literal, Optional, Protocol
from django.db.models import F
@@ -551,6 +552,41 @@ POST_LOAD_STEPS: tuple[PostLoadStep, ...] = (
)
+def _repartitioned_during_job(schema: ExternalDataSchema, job: ExternalDataJob) -> bool:
+ """Whether a repartition rewrote the table earlier in this same job.
+
+ The swap clears `repartition_pending` and `repartition_swap` before extraction runs, so
+ those markers cannot tell post-load that the layout was just replaced and its files still
+ need publishing. An unparseable stamp publishes rather than skips.
+ """
+ stamped = schema.last_repartition_at
+ if not stamped:
+ return False
+ try:
+ return dt.datetime.fromisoformat(stamped) >= job.created_at
+ except (TypeError, ValueError):
+ return True
+
+
+async def _run_post_load_steps(
+ job: ExternalDataJob,
+ schema: ExternalDataSchema,
+ source: "ExternalDataSource",
+ delta_table_ref: "DeltaTableRef",
+ is_cdc_companion: bool,
+ logger: FilteringBoundLogger,
+) -> None:
+ for step in POST_LOAD_STEPS:
+ await step(
+ job=job,
+ schema=schema,
+ source=source,
+ delta_table_ref=delta_table_ref,
+ is_cdc_companion=is_cdc_companion,
+ logger=logger,
+ )
+
+
async def run_post_load_operations(
job: ExternalDataJob,
schema: ExternalDataSchema,
@@ -563,6 +599,7 @@ async def run_post_load_operations(
last_incremental_field_value: Any = None,
resource: "Optional[SourceResponse]" = None,
cdc_write_mode: Optional[str] = None,
+ allow_zero_row_skip: bool = False,
) -> Optional[str]:
"""
Orchestrator that runs all post-load operations, in order:
@@ -575,6 +612,9 @@ async def run_post_load_operations(
analytics views, repartition detection)
Returns the queryable folder the table now serves from, or None when there is no delta table.
+
+ With `allow_zero_row_skip`, a steady-state non-CDC run that wrote zero rows skips steps
+ 1, 2 and 4 and returns None.
"""
if delta_table_ref is None or await delta_table_ref.get_delta_table() is None:
logger.debug("No deltalake table, not continuing with post-run ops")
@@ -589,6 +629,28 @@ async def run_post_load_operations(
# look like a continuation.
is_initial_load = not schema.initial_sync_complete
+ # Zero rows means the Delta table is untouched: nothing to compact, and republishing
+ # would only orphan a fresh copy of every parquet file. Registration already no-ops at
+ # zero rows. Bookkeeping and POST_LOAD_STEPS still run below, because those repair
+ # managed views and watermarks rather than describing what this run wrote. Opt-in
+ # because only the v2 pipeline's row_count is ground truth for what the run wrote; the
+ # v3 consumer's can read 0 for a batch that did write data.
+ if (
+ allow_zero_row_skip
+ and row_count == 0
+ and not is_cdc_schema
+ and not is_cdc_companion
+ and schema.initial_sync_complete
+ and schema.repartition_pending is None
+ and schema.repartition_swap is None
+ and schema.delta_revive_required is None
+ and not _repartitioned_during_job(schema, job)
+ ):
+ logger.debug("Zero rows synced, skipping delta maintenance and S3 publish")
+ await _finalize_sync_bookkeeping(job, schema, resource, last_incremental_field_value, logger)
+ await _run_post_load_steps(job, schema, source, delta_table_ref, is_cdc_companion, logger)
+ return None
+
await _run_delta_maintenance(schema, delta_table_ref, is_cdc_companion, logger)
queryable_folder = await _publish_queryable_files(
@@ -621,14 +683,6 @@ async def run_post_load_operations(
logger=logger,
)
- for step in POST_LOAD_STEPS:
- await step(
- job=job,
- schema=schema,
- source=source,
- delta_table_ref=delta_table_ref,
- is_cdc_companion=is_cdc_companion,
- logger=logger,
- )
+ await _run_post_load_steps(job, schema, source, delta_table_ref, is_cdc_companion, logger)
return queryable_folder
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
index 5fc091df605b..7285542f3c4c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py
@@ -1,4 +1,5 @@
import uuid
+from datetime import UTC, datetime
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -23,6 +24,7 @@ _LOAD_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelin
_DB_RETRY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry"
_PIPELINE_SYNC_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync"
_REPARTITION_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition_controller"
+_JOB_CREATED_AT = datetime(2026, 8, 19, 11, 0, tzinfo=UTC)
def _make_schema(
@@ -180,6 +182,121 @@ class TestRunPostLoadDeltaMaintenance:
prepare_s3.assert_awaited_once()
+class TestZeroRowSkip:
+ @parameterized.expand(
+ [
+ ("steady_state_zero_rows_skips", 0, "incremental", True, {}, True, True),
+ ("synced_rows_run_full_path", 5, "incremental", True, {}, True, False),
+ ("caller_without_opt_in_runs_full_path", 0, "incremental", True, {}, False, False),
+ ("incomplete_initial_sync_runs_full_path", 0, "incremental", False, {}, True, False),
+ ("cdc_schema_runs_full_path", 0, "cdc", True, {}, True, False),
+ (
+ "repartition_pending_runs_full_path",
+ 0,
+ "incremental",
+ True,
+ {"repartition_pending": {"m": 1}},
+ True,
+ False,
+ ),
+ ("repartition_swap_runs_full_path", 0, "incremental", True, {"repartition_swap": {"c": "x"}}, True, False),
+ (
+ "revive_marker_runs_full_path",
+ 0,
+ "incremental",
+ True,
+ {"delta_revive_required": {"r": "h"}},
+ True,
+ False,
+ ),
+ (
+ "repartition_completed_this_job_runs_full_path",
+ 0,
+ "incremental",
+ True,
+ {"last_repartition_at": "2026-08-19T12:00:00+00:00"},
+ True,
+ False,
+ ),
+ (
+ "repartition_completed_before_this_job_skips",
+ 0,
+ "incremental",
+ True,
+ {"last_repartition_at": "2026-08-19T10:00:00+00:00"},
+ True,
+ True,
+ ),
+ (
+ "unparseable_repartition_stamp_runs_full_path",
+ 0,
+ "incremental",
+ True,
+ {"last_repartition_at": "not-a-date"},
+ True,
+ False,
+ ),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_zero_row_runs_skip_maintenance_and_publish(
+ self,
+ _name: str,
+ row_count: int,
+ sync_type: str,
+ initial_sync_complete: bool,
+ sync_type_config: dict,
+ allow_zero_row_skip: bool,
+ expect_skip: bool,
+ ):
+ schema = ExternalDataSchema(
+ id=uuid.uuid4(),
+ name="Customer",
+ sync_type=sync_type,
+ initial_sync_complete=initial_sync_complete,
+ sync_type_config=sync_type_config,
+ )
+ job = MagicMock()
+ job.id = uuid.uuid4()
+ job.team_id = 1
+ job.created_at = _JOB_CREATED_AT
+
+ maintenance = AsyncMock()
+ publish = AsyncMock(return_value="folder")
+ bookkeeping = AsyncMock()
+ post_load_step = AsyncMock()
+ with (
+ patch(f"{_LOAD_MODULE}._run_delta_maintenance", maintenance),
+ patch(f"{_LOAD_MODULE}._publish_queryable_files", publish),
+ patch(f"{_LOAD_MODULE}._finalize_sync_bookkeeping", bookkeeping),
+ patch(f"{_LOAD_MODULE}._register_table", AsyncMock()),
+ patch(f"{_LOAD_MODULE}._run_cdc_post_load", AsyncMock()),
+ patch(f"{_LOAD_MODULE}.POST_LOAD_STEPS", (post_load_step,)),
+ ):
+ result = await run_post_load_operations(
+ job=job,
+ schema=schema,
+ source=MagicMock(),
+ delta_table_ref=_make_helper(),
+ row_count=row_count,
+ table_schema_dict={},
+ resource_name="customer",
+ logger=MagicMock(),
+ allow_zero_row_skip=allow_zero_row_skip,
+ )
+
+ bookkeeping.assert_awaited_once()
+ post_load_step.assert_awaited_once()
+ if expect_skip:
+ maintenance.assert_not_awaited()
+ publish.assert_not_awaited()
+ assert result is None
+ else:
+ maintenance.assert_awaited_once()
+ publish.assert_awaited_once()
+ assert result == "folder"
+
+
class TestCdcCompanionSeeding:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
index 5337347fc544..e69dd380a891 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
@@ -450,6 +450,7 @@ class PipelineNonDLT(Generic[ResumableData]):
logger=self._logger,
last_incremental_field_value=self._last_incremental_field_value,
resource=self._resource,
+ allow_zero_row_skip=True,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py
index 1d6aa798de7c..8afee8f6e6cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py
@@ -169,6 +169,12 @@ def _always(gate: PostImportGateContext) -> bool:
return True
+def _wrote_rows_gate(gate: PostImportGateContext) -> bool:
+ """Table size describes the rows this run loaded, so a run that wrote none leaves it
+ unchanged. `None` predates row counting, so it runs the step."""
+ return gate.job.rows_synced != 0
+
+
def _data_quality_gate(gate: PostImportGateContext) -> bool:
return data_quality_checks_needed_for(gate.team_id, gate.schema.table_id)
@@ -309,7 +315,7 @@ POST_IMPORT_STEPS: tuple[PostImportStep, ...] = (
PostImportStep(key=EMIT_SIGNALS_STEP, enabled=_emit_signals_gate, start=_start_emit_signals),
PostImportStep(key=SEMANTIC_ENRICHMENT_STEP, enabled=_enrichment_gate, start=_start_semantic_enrichment),
PostImportStep(key=TABLE_STATISTICS_STEP, enabled=_statistics_gate, start=_start_table_statistics),
- PostImportStep(key=TABLE_SIZE_STEP, enabled=_always, start=_start_table_size),
+ PostImportStep(key=TABLE_SIZE_STEP, enabled=_wrote_rows_gate, start=_start_table_size),
PostImportStep(key=DUCKLAKE_COPY_STEP, enabled=_always, start=_start_ducklake_copy),
PostImportStep(key=DATA_QUALITY_CHECKS_STEP, enabled=_data_quality_gate, start=_start_data_quality_checks),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
index 06a3b3baef3a..a9a093661cd8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_post_import_fork.py
@@ -367,7 +367,7 @@ def _no_close_old_connections():
yield
-def _create_job(team, *, status, schema_snapshot, schema_last_synced_at):
+def _create_job(team, *, status, schema_snapshot, schema_last_synced_at, rows_synced=5):
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -382,7 +382,7 @@ def _create_job(team, *, status, schema_snapshot, schema_last_synced_at):
schema=schema,
status=status,
schema_snapshot=schema_snapshot,
- rows_synced=0,
+ rows_synced=rows_synced,
)
return source, schema, job
@@ -425,6 +425,46 @@ def test_resolve_context_uses_pre_sync_watermark_from_snapshot(team, _no_close_o
assert ctx.steps[-2:] == [TABLE_SIZE_STEP, DUCKLAKE_COPY_STEP]
+ "rows_synced,expect_steps",
+ [
+ pytest.param(5, True, id="rows_written"),
+ pytest.param(0, False, id="zero_rows"),
+ pytest.param(None, True, id="row_count_unknown"),
+ ],
+)
+def test_table_size_tracks_rows_written_while_ducklake_copy_always_runs(
+ team, rows_synced, expect_steps, _no_close_old_connections
+):
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+ from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (
+ DUCKLAKE_COPY_STEP,
+ TABLE_SIZE_STEP,
+ PostImportWorkflowInputs,
+ resolve_post_import_context_activity,
+ )
+
+ source, schema, job = _create_job(
+ team,
+ status=ExternalDataJob.Status.COMPLETED,
+ schema_snapshot={"last_synced_at": "2026-07-01T00:00:00+00:00"},
+ schema_last_synced_at=None,
+ rows_synced=rows_synced,
+ )
+
+ ctx = resolve_post_import_context_activity(
+ PostImportWorkflowInputs(
+ team_id=team.pk, job_id=str(job.id), schema_id=str(schema.id), source_id=str(source.id)
+ )
+ )
+
+ assert ctx.steps is not None
+ assert (TABLE_SIZE_STEP in ctx.steps) is expect_steps
+ # The sync path is the only retry for a failed DuckLake copy, so it runs even at zero rows.
+ assert DUCKLAKE_COPY_STEP in ctx.steps
+
+
@pytest.mark.django_db
@pytest.mark.parametrize("case", ["job_deleted", "job_not_completed"])
def test_resolve_context_skips_all_steps_when_job_is_gone_or_not_completed(team, case, _no_close_old_connections):