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.

chore(data-warehouse): remove the v2 import pipeline (#112145)

Tom Owers39b18e516fa9
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index e9c24be3b22f..d5c9f8ccef81 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -383,7 +383,7 @@ Return a `SourceResponse` directly. **Do not** use `dlt_source_to_source_respons
Prefer yielding data in the shape the API returns it. No custom dataclasses, no heavy parsing. Yield either `dict`, `list[dict]` (preferred when possible), or a `pyarrow.Table`. The pipeline buffers and batches for you.
-**Default to yielding raw `dict` / `list[dict]` and let the pipeline batch for you.** The pipeline already runs a `Batcher` (`pipelines/pipeline_v2/pipeline.py`) at 5000-row / 200 MiB thresholds, so the common case needs no batcher of its own. Reach for `pyarrow.Table` only when you already have arrow-shaped data (e.g. a ClickHouse adapter). A source _may_ instantiate its own `Batcher` with **smaller** thresholds (e.g. `chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024`, as klaviyo and ~70 other sources do) when it deliberately wants a tighter memory footprint for large/wide rows — that's a valid choice, not the default. What to avoid is a second _full-size_ batcher, which just double-buffers with no win.
+**Default to yielding raw `dict` / `list[dict]` and let the pipeline batch for you.** The pipeline already runs a `Batcher` (`pipelines/pipeline_v3/pipeline.py`) at 5000-row / 200 MiB thresholds, so the common case needs no batcher of its own. Reach for `pyarrow.Table` only when you already have arrow-shaped data (e.g. a ClickHouse adapter). A source _may_ instantiate its own `Batcher` with **smaller** thresholds (e.g. `chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024`, as klaviyo and ~70 other sources do) when it deliberately wants a tighter memory footprint for large/wide rows — that's a valid choice, not the default. What to avoid is a second _full-size_ batcher, which just double-buffers with no win.
For pyarrow tables, cap in-memory rows at ~200 MiB or ~5000 rows. Use helpers like `table_from_iterator()` / `table_from_py_list()` from `products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py`.
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 8415c536238d..7199c56f5ab1 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -1205,7 +1205,7 @@ def send_external_data_failure_digest(team_id: int, schemas: list[dict[str, Any]
# Rollout gate (absent flag = off). Gated teams are never stamped, so when the
# flag opens up the catch-up delivers their currently-failing schemas naturally.
- # group_properties mirror the warehouse-pipelines-v3 gate (create_job_model.py):
+ # group_properties mirror the warehouse-multi-destination gate (destinations/enablement.py):
# without them, release conditions on the project/organization group can't match,
# because the analytics group records are keyed by uuid rather than team_id/org_id.
if not settings.TEST and not posthoganalytics.feature_enabled(
diff --git a/products/warehouse_sources/backend/facade/pipelines.py b/products/warehouse_sources/backend/facade/pipelines.py
index 9835970aeedc..c439baab5c06 100644
--- a/products/warehouse_sources/backend/facade/pipelines.py
+++ b/products/warehouse_sources/backend/facade/pipelines.py
@@ -2,9 +2,9 @@
Pipeline/metrics wiring for warehouse_sources.
Re-exports the data-import pipeline internals (v3 S3 helpers and health server),
-the app-metric emitters, the CDC extraction input, and the pipeline-
-version + schema-sync helpers that sibling products (data_warehouse, error_tracking) and
-core (the ducklake copy workflow) reach into while orchestrating or observing imports.
+the app-metric emitters, the CDC extraction input, and the schema-sync helpers that
+sibling products (data_warehouse, error_tracking) and core (the ducklake copy workflow)
+reach into while orchestrating or observing imports.
These live deep under ``temporal.data_imports`` and pull heavy dependencies (temporalio,
dlt, boto3, ...), so — like ``facade.source_management`` — the module resolves names lazily
@@ -22,7 +22,6 @@ _LAZY = {
"mark_job_failed_if_not_terminal": "pipelines.pipeline_v3.postgres_queue.consumer",
"release_v3_pipeline_lock": "pipelines.pipeline_v3.sync_lock",
"CDCExtractionInput": "cdc.workflows",
- "is_pipeline_v3_enabled": "workflow_activities.create_job_model",
"SyncNewSchemasActivityInputs": "workflow_activities.sync_new_schemas",
"finish_row_tracking": "row_tracking",
"HealthState": "products.warehouse_sources_queue.backend.core.health",
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 0bd1978d2055..66d8fd683c36 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1786,7 +1786,7 @@ def mark_schema_running_unless_halted(schema: ExternalDataSchema) -> bool:
def mark_initial_sync_complete(schema_id: str | uuid.UUID, team_id: int) -> None:
- """Mark a schema's first successful sync complete. Shared by the V2 pipelines and the V3 loader.
+ """Mark a schema's first successful sync complete. Called by the V3 loader's post-load.
On the False→True transition, a CDC schema still in snapshot mode moves to
``cdc_mode="streaming"`` in the same row lock. Callers must only invoke this once the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/HISTORY.md b/products/warehouse_sources/backend/temporal/data_imports/HISTORY.md
index 01afc098d39c..bef39a28a256 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/HISTORY.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/HISTORY.md
@@ -57,12 +57,6 @@ We merge data into deltalake one partition at a time, deltalake doesn't support
We have a handful of tables that require a parent object to cursor, for example, Stripe invoice line items requires a Stripe invoice object, and so we have to list the invoices, and then iterate each line item for each invoice. It'd be good if we were able to utilize existing tables for these nested dependent tables
-##### 7 - PipelineNonDLT duplicate-data race on resume
-
-`products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py` (PipelineNonDLT) can produce duplicate rows in the destination when a pod dies between a successful `write_to_deltalake` commit and the source's subsequent `ResumableSourceManager.save_state` Redis write.
-On resume, the stale Redis cursor causes the source to re-fetch rows that already landed in delta, and the re-fetched batch is appended without dedup.
-This was not fixed because PipelineNonDLT is being retired in favor of `pipeline_v3`; the equivalent writer-side idempotency gap in v3 _was_ fixed by tagging delta commits with `(run_uuid, batch_index)` in their `custom_metadata` so the idempotency check can fall back to delta history when the Redis dedup flag is missing.
-
### Proposed pipeline
- Generally a more producer/consumer approach
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py
index fe073353fbbe..acfc0f0f1134 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py
@@ -133,12 +133,6 @@ class TestBufferedDispatch:
modes = [lane.cdc_write_mode for lane in response.lanes or []]
assert modes == ["incremental_merge", "scd2_append"]
- def test_a_v2_run_reaching_the_buffered_lane_fails_loudly(self):
- # The forcing keeps this unreachable; if a race or deploy skew gets past it, the run must
- # fail rather than consume without recording a load position.
- with pytest.raises(ValueError, match="requires v3"):
- _dispatch(_schema(), _inputs(), job_version="v2-non-dlt")
-
def test_a_missing_job_row_fails_the_run(self):
# Every lane reads its resume point off its own Delta table, which needs the job row.
with pytest.raises(ValueError, match="no job row"):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py
index e0161a58ebb5..084f4704d06e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py
@@ -29,8 +29,8 @@ WAREHOUSE_MULTI_DESTINATION_FLAG = "warehouse-multi-destination"
def is_multi_destination_enabled(team_id: int, source_type: str) -> bool:
"""Whether this team's syncs of this source type deliver to configured destinations.
- Evaluated in an activity and carried into the workflow as recorded history, the same way
- the v3 rollout flag is — a workflow must never read a flag directly.
+ Evaluated in an activity and carried into the workflow as recorded history — a workflow must
+ never read a flag directly.
"""
try:
team = Team.objects.only("uuid", "organization_id").get(id=team_id)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 5d2401092bc1..77928d62a87e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -801,40 +801,45 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
consumer_manages_job_status = False
skip_post_import_activities = False
workflow_starts_post_import = False
- is_v3 = False
+ is_v3 = True
lock_token = None
- # Check pipeline version (FF evaluated once here, propagated everywhere)
- try:
- version_result = await workflow.execute_activity(
- check_pipeline_version_activity,
- CheckPipelineVersionActivityInputs(
- team_id=inputs.team_id,
- source_id=inputs.external_data_source_id,
- schema_id=inputs.external_data_schema_id,
- ),
- start_to_close_timeout=dt.timedelta(minutes=1),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
- is_v3 = version_result.is_v3
- except Exception:
- # Guessing the version is not safe: a buffered CDC schema consumed on v2 records no
- # load position, so the buffer re-merges in full and nothing is ever deleted. Skip
- # the run and let the schedule fire again, matching the lock-not-acquired path.
- # patched() keeps in-flight pre-patch executions replaying their recorded fall-through.
- if workflow.patched("data-imports-skip-run-on-version-check-failure-v1"):
- workflow.logger.error(
- "Failed to check pipeline version, skipping run",
+ # Every run is V3. A history recorded before this patch scheduled the version check as
+ # its first command, so the else branch keeps that command sequence for replay.
+ # TODO: swap to workflow.deprecate_patch and delete the else branch once no pre-patch
+ # executions remain.
+ if not workflow.patched("data-imports-v3-only-2026-10"):
+ is_v3 = False
+ try:
+ version_result = await workflow.execute_activity(
+ check_pipeline_version_activity,
+ CheckPipelineVersionActivityInputs(
+ team_id=inputs.team_id,
+ source_id=inputs.external_data_source_id,
+ schema_id=inputs.external_data_schema_id,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ is_v3 = version_result.is_v3
+ except Exception:
+ # Guessing the version is not safe: a buffered CDC schema consumed on v2 records no
+ # load position, so the buffer re-merges in full and nothing is ever deleted. Skip
+ # the run and let the schedule fire again, matching the lock-not-acquired path.
+ # patched() keeps in-flight pre-patch executions replaying their recorded fall-through.
+ if workflow.patched("data-imports-skip-run-on-version-check-failure-v1"):
+ workflow.logger.error(
+ "Failed to check pipeline version, skipping run",
+ extra={"schema_id": str(inputs.external_data_schema_id)},
+ )
+ get_version_check_skipped_metric().add(1)
+ return
+ workflow.logger.warning(
+ "Failed to check pipeline version, defaulting to V2",
extra={"schema_id": str(inputs.external_data_schema_id)},
)
- get_version_check_skipped_metric().add(1)
- return
- workflow.logger.warning(
- "Failed to check pipeline version, defaulting to V2",
- extra={"schema_id": str(inputs.external_data_schema_id)},
- )
- # Only acquire lock for V3 pipelines (V2 never enters this block)
+ # Only a pre-patch replay that recorded a V2 version check skips the lock.
if is_v3:
lock_result = None
try:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
index d90cf6ba8f80..358fa6dee70e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/README.md
@@ -7,9 +7,9 @@ This page is the map; each package's own docstrings and READMEs carry the detail
## The sync flow
1. A per-schema Temporal schedule fires `ExternalDataJobWorkflow` (`../external_data_job.py`).
-2. The workflow evaluates the v3 rollout flag once (`check_pipeline_version_activity`) and, for v3, takes the per-schema Redis sync lock (`pipeline_v3/sync_lock.py`).
-3. `create_external_data_job_model_activity` creates the job row and persists `pipeline_version` on it - the single source of truth every later step consults.
-4. `import_data_activity_sync` (`../workflow_activities/import_data_sync.py`) builds the source's `SourceResponse` and runs the pipeline the persisted version selects.
+2. The workflow takes the per-schema Redis sync lock (`pipeline_v3/sync_lock.py`).
+3. `create_external_data_job_model_activity` creates the job row with `pipeline_version` set to V3.
+4. `import_data_activity_sync` (`../workflow_activities/import_data_sync.py`) builds the source's `SourceResponse` and runs the v3 extraction. It fails a job row with any other pipeline version.
5. Post-load (`common/load.py::run_post_load_operations`): delta maintenance, publish queryable files, register the table, CDC companion handling, `POST_LOAD_STEPS`.
6. Finalization (terminal job status, v3 lock release, post-import start) is owned per run: the workflow, or the v3 load consumer once it loads the final batch.
The contract lives on the `PipelineResult` docstring (`core/typings.py`).
@@ -40,23 +40,22 @@ CDC is excluded for now: the source setup flow does not offer destinations for C
| Pipeline | Lives in | Attaches at |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| v2 extract+load (`PipelineNonDLT`) | `pipeline_v2/` | Step 4 when `pipeline_version == V2`; writes Delta inline per chunk, so extract and load are one activity. The workflow finalizes. |
-| v3 extract (`PipelineV3`) | `pipeline_v3/pipeline.py`, `pipeline_v3/s3/`, `pipeline_v3/postgres_queue/producer.py` | Step 4 when `pipeline_version == V3`, under the sync lock; writes parquet batches to S3 and enqueues them (`ExportSignalMessage`, `pipeline_v3/messages.py`) on the Postgres load queue. |
+| v3 extract (`PipelineV3`) | `pipeline_v3/pipeline.py`, `pipeline_v3/s3/`, `pipeline_v3/postgres_queue/producer.py` | Step 4, under the sync lock; writes parquet batches to S3 and enqueues them (`ExportSignalMessage`, `pipeline_v3/messages.py`) on the Postgres load queue. |
| v3 load | `pipeline_v3/postgres_queue/`, `pipeline_v3/load/`, engine in `products/warehouse_sources_queue/backend/core/` | Its own deployment (`run_warehouse_sources_load`), not the workflow: claims queued batches, writes Delta via `core/delta/`, finalizes the job, releases the lock, starts post-import. When the run has destinations it also hands each batch to `destinations_load/delivery.py` before finalizing. |
| CDC | `../cdc/` | Capture runs outside the scheduled flow: the `cdc-extraction` Temporal workflow tails the source WAL and writes change files to the S3 change buffer (`cdc/buffer.py`). Each table's scheduled v3 sync consumes that buffer as its source (`cdc/source_manager.py`); the loader writes the consolidated table and the `_cdc` SCD2 companion (`core/delta/scd2.py`). |
| Webhooks | `run_webhook_s3_sink` command; sink behind the `data_warehouse` facade | Buffered ingress: deliveries are buffered to S3 continuously, and the next scheduled sync drains them as ordinary source items (webhook-only schemas skip table resets, `common/extract.py`). |
-| Chunk sinks (CDP, person properties) | `core/sinks.py`, `core/cdp_producer.py`, `core/person_property_row_sink.py` | Gated taps on both write loops, one `stage_chunk` call per chunk (see `ChunkSink`). Downstream: `dwh-cdp-producer-job` produces staged chunks to Kafka for HogFunctions/HogFlows; `sync-warehouse-person-properties` plus `run_person_property_update_consumer` upsert person properties. |
+| Chunk sinks (CDP, person properties) | `core/sinks.py`, `core/cdp_producer.py`, `core/person_property_row_sink.py` | Gated taps on the write loop, one `stage_chunk` call per chunk (see `ChunkSink`). Downstream: `dwh-cdp-producer-job` produces staged chunks to Kafka for HogFunctions/HogFlows; `sync-warehouse-person-properties` plus `run_person_property_update_consumer` upsert person properties. |
| Post-import steps | `../post_import_job.py`, children under `../workflow_activities/` | Step 7. Started by whoever finalizes the run (step 6); gates are resolved once in its resolve activity, then the workflow is a loop over recorded step keys. |
| Repartition | `core/repartition.py`, `core/repartition_controller.py`, `../workflow_activities/repartition_table.py` | Detection is a `POST_LOAD_STEPS` entry (flags oversized partitions); execution is `maybe_repartition_table_activity`, pre-extraction on the next run while the lock is held. |
## The shared kernel
-- `core/` - version-neutral pieces both pipelines use: `batcher.py`, `arrow_utils.py`, `partitioning.py`, `hogql_schema.py`, `sinks.py`, the repartitioner, and `typings.py` (`PipelineResult`).
+- `core/` - the pipeline kernel: `batcher.py`, `arrow_utils.py`, `partitioning.py`, `hogql_schema.py`, `sinks.py`, the repartitioner, and `typings.py` (`PipelineResult`).
- `core/delta/` - everything Delta Lake, one concern per module: `table.py` (`DeltaTableRef`, the single stateful handle threaded through a run), `writer.py`, `scd2.py`, `maintenance.py`, `evolution.py`, `ops.py`, `errors.py`.
The write/maintenance classes are stateless wrappers constructed at their call sites over a `DeltaTableRef`.
-- `common/` - the sync-flow helpers shared by v2 and v3: `extract.py` (reset/corruption handling, incremental bookkeeping) and `load.py` (`run_post_load_operations`).
+- `common/` - the sync-flow helpers: `extract.py` (reset/corruption handling, incremental bookkeeping) and `load.py` (`run_post_load_operations`).
- `pipeline_sync.py`, `helpers.py` - table registration and naming.
-Dependency rule: `pipeline_v2/` and `pipeline_v3/` import from `core/` and `common/`; `core/` imports from no pipeline.
+Dependency rule: `pipeline_v3/` imports from `core/` and `common/`; `core/` imports from no pipeline.
One remaining exception: several `core/` modules still import the shared write metrics from `pipeline_v3/load/metrics.py`.
Cross-product coupling goes through `../external_product_hooks.py` (registration) rather than direct imports.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 002db4c94ed6..fee94fc0ba35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -331,27 +331,14 @@ async def handle_non_retryable_error(
raise NonRetryableException() from error
-async def reset_rows_synced_if_needed(
- job: "ExternalDataJob",
- is_incremental: bool,
- reset_pipeline: bool,
- should_resume: bool,
- *,
- incremental_cursor_staged: bool = False,
-) -> None:
+async def reset_rows_synced_if_needed(job: "ExternalDataJob", should_resume: bool) -> None:
# Reset the rows_synced count - this may not be 0 if the job restarted due to a heartbeat timeout.
#
- # Incremental syncs are exempt only when the durable cursor advances per batch (pipeline v2), so
- # a retried attempt resumes past the rows already counted. When the cursor is staged and only
- # promoted on completion (pipeline v3), a retried attempt re-extracts the whole window from
- # batch 0, so keeping the previous attempt's count double-counts every re-read row —
- # `rows_synced` feeds billed usage via `Sum("rows_synced")` in usage reports.
- if (
- job.rows_synced is not None
- and job.rows_synced != 0
- and (not is_incremental or reset_pipeline is True or incremental_cursor_staged)
- and not should_resume
- ):
+ # The incremental cursor is staged and only promoted on completion, so a retried attempt
+ # re-extracts the whole window from batch 0, and keeping the previous attempt's count
+ # double-counts every re-read row — `rows_synced` feeds billed usage via `Sum("rows_synced")`
+ # in usage reports. A resumed attempt picks up the earlier attempt's staged batches instead.
+ if job.rows_synced is not None and job.rows_synced != 0 and not should_resume:
job.rows_synced = 0
await database_sync_to_async_pool(job.save)(update_fields=["rows_synced", "updated_at"])
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 828eed071848..178f35c7ed61 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,4 +1,3 @@
-import datetime as dt
from typing import TYPE_CHECKING, Any, Literal, Optional, Protocol
from django.db.models import F
@@ -592,22 +591,6 @@ 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
-
-
def _post_load_step_phase_name(step: PostLoadStep) -> str:
name = getattr(step, "__name__", type(step).__name__)
return name.strip("_").removesuffix("_step")
@@ -645,7 +628,6 @@ 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:
@@ -658,9 +640,6 @@ 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:
# A clean run that wrote zero rows creates no delta table, so there is nothing to publish or
@@ -680,31 +659,6 @@ 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. A schema with a linked table
- # has nothing to repoint either. 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
- # An unlinked schema has nothing queryable, and skipping registration strands it: the next
- # zero-row run skips again.
- and schema.table_id is not None
- 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(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
index a86202c6cedf..76fa08df75c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
@@ -608,39 +608,26 @@ class TestResetRowsSyncedIfNeeded:
)
@pytest.mark.parametrize(
- "_name,is_incremental,reset_pipeline,should_resume,incremental_cursor_staged,expect_reset",
+ "_name,should_resume,expect_reset",
[
- # Staged-cursor (v3) incremental retry re-extracts the whole window from batch 0, so a
- # leftover count from the previous attempt would double-count every re-read row — and
- # rows_synced feeds billed usage. This is the regression case.
- ("staged_cursor_incremental_retry_resets", True, False, False, True, True),
+ # A retry re-extracts the whole window from batch 0, so a leftover count from the
+ # previous attempt would double-count every re-read row — and rows_synced feeds
+ # billed usage. This is the regression case.
+ ("retry_resets", False, True),
# A resumable source picks up the previous attempt's staged batches, so its rows stay counted.
- ("resumable_source_keeps_count", True, False, True, True, False),
- # Durable-cursor (v2) incremental retry resumes past the rows already counted.
- ("durable_cursor_incremental_retry_keeps_count", True, False, False, False, False),
- ("full_refresh_restart_resets", False, False, False, False, True),
- ("reset_pipeline_resets", True, True, False, False, True),
+ ("resumable_source_keeps_count", True, False),
],
)
def test_reset_conditions(
self,
_name: str,
- is_incremental: bool,
- reset_pipeline: bool,
should_resume: bool,
- incremental_cursor_staged: bool,
expect_reset: bool,
team,
) -> None:
job = self._job_with_leftover_count(team)
- async_to_sync(reset_rows_synced_if_needed)(
- job,
- is_incremental,
- reset_pipeline,
- should_resume,
- incremental_cursor_staged=incremental_cursor_staged,
- )
+ async_to_sync(reset_rows_synced_if_needed)(job, should_resume)
job.refresh_from_db()
assert job.rows_synced == (0 if expect_reset else 1234)
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 901875ed83c4..0655ebd27049 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
@@ -34,8 +34,6 @@ _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)
-_A_LINKED_TABLE_ID = uuid.uuid4()
def _make_schema(
@@ -289,125 +287,6 @@ class TestPublishQueryableFilesDoubleBuffer:
assert prepare_s3.await_args.kwargs["pointer_history"] == expected_history
-class TestZeroRowSkip:
- @parameterized.expand(
- [
- ("steady_state_zero_rows_skips", 0, "incremental", True, {}, True, True),
- ("synced_rows_run_full_path", 5, "incremental", True, {}, True, False),
- # An unlinked schema has nothing queryable, and a skip here strands it forever.
- ("unlinked_schema_runs_full_path", 0, "incremental", True, {}, True, False, None),
- ("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,
- table_id: Optional[uuid.UUID] = _A_LINKED_TABLE_ID,
- ):
- schema = ExternalDataSchema(
- id=uuid.uuid4(),
- name="Customer",
- sync_type=sync_type,
- initial_sync_complete=initial_sync_complete,
- sync_type_config=sync_type_config,
- table_id=table_id,
- )
- 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/core/post_load_phases.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/post_load_phases.py
index b3608a6de5f4..01ad35472340 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/post_load_phases.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/post_load_phases.py
@@ -2,7 +2,7 @@
The loader opens one recorder for each final batch with ``record_post_load_phases``. Code on the
post-load path marks its steps with ``post_load_phase`` or ``recorded_phase``. These do nothing when
-no recorder is active, so the same code runs unchanged on the pre-write path and in the v2 pipeline.
+no recorder is active, so the same code runs unchanged on the pre-write path.
When the batch completes, the recorder writes one log line that lists every phase.
The recorder is observability only. An error inside it is logged at debug and never reaches the load.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
index 8ae4984b3ff0..c67b0cc77a6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/typings.py
@@ -8,8 +8,8 @@ class PipelineResult(TypedDict):
writes the terminal job status, releases the v3 sync lock, and starts the post-import
workflow:
- - False / absent (v2, and every failure path — an activity that raises returns no result):
- the workflow finalizes in its `finally` block.
+ - False / absent (a zero-batch run, and every failure path — an activity that raises returns
+ no result): the workflow finalizes in its `finally` block.
- True: the v3 load consumer finalizes after loading the final batch, and the workflow must
keep its hands off all three.
@@ -20,7 +20,7 @@ class PipelineResult(TypedDict):
`import_data_sync`'s terminal-retry skip, is a run some other party already finalized, where
True likewise means "workflow: hands off".
Making this a pure version property requires an empty-final-batch queue message so the
- consumer hears about every v3 run — deferred until the v2 pipeline is deleted.
+ consumer hears about every v3 run.
`fast_returned` marks a run completed on a negative source probe, before any extraction.
It always rides with `skip_post_import_activities=True` (which does the actual skipping);
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
deleted file mode 100644
index cbe96c3db48c..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ /dev/null
@@ -1,537 +0,0 @@
-import sys
-import time
-import asyncio
-import contextlib
-from typing import TYPE_CHECKING, Any, Generic, Literal
-
-import pyarrow as pa
-import deltalake as deltalake
-from structlog.types import FilteringBoundLogger
-
-from posthog.exceptions_capture import capture_exception
-from posthog.sync import database_sync_to_async_pool
-from posthog.temporal.common.shutdown import ShutdownMonitor
-
-from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import (
- ExternalDataSchema,
- process_incremental_value,
- update_sync_type_config_keys,
-)
-from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-from products.warehouse_sources.backend.models.table import DataWarehouseTable
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
- cleanup_memory,
- commit_source_cursor,
- handle_corrupted_delta_log,
- handle_reset_or_full_refresh,
- persist_primary_keys,
- reset_rows_synced_if_needed,
- resolve_primary_keys,
- setup_row_tracking_with_billing_check,
- should_check_shutdown,
- update_incremental_field_values,
- update_row_tracking_after_batch,
- validate_incremental_sync,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (
- run_post_load_operations,
- supports_partial_data_loading,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.safe_point import (
- PipelineSafePointHandler,
- source_items_are_framework_output,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
- _append_debug_column_to_pyarrows_table,
- _handle_null_columns_with_definitions,
- evolve_pyarrow_schema,
- merge_observed_columns_into_schema_metadata,
- normalize_table_column_names,
- observe_and_project_table,
- source_uses_delta_write_column_selection,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.async_iterate import async_iterate
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
-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.hogql_schema import HogQLSchema
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import setup_partitioning
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.sinks import (
- PipelineSinks,
- build_pipeline_sinks,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import record_source_item_stats
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
- validate_schema_and_update_table,
-)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import (
- ResumableSourceManager,
- resolve_resume_manager,
-)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_point
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
- ResumableData,
- SourceResponse,
-)
-from products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying
-
-if TYPE_CHECKING:
- from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
- ImportJobModels,
- )
-
-
-class PipelineNonDLT(Generic[ResumableData]):
- _resource: SourceResponse
- _resource_name: str
- _job: ExternalDataJob
- _source: ExternalDataSource
- _schema: ExternalDataSchema
- _table: DataWarehouseTable | None
- _logger: FilteringBoundLogger
- _is_incremental: bool
- _reset_pipeline: bool
- _delta_table_ref: DeltaTableRef
- _resumable_source_manager: ResumableSourceManager[ResumableData] | None
- _source_cursor_manager: SourceCursorManager[Any] | None
- _internal_schema = HogQLSchema()
- _sinks: PipelineSinks
- _batcher: Batcher
- _load_id: int
-
- def __init__(
- self,
- source_response: SourceResponse,
- logger: FilteringBoundLogger,
- job_id: str,
- reset_pipeline: bool,
- shutdown_monitor: ShutdownMonitor,
- resumable_source_manager: ResumableSourceManager[ResumableData] | None,
- *,
- models: "ImportJobModels",
- source_cursor_manager: SourceCursorManager[Any] | None = None,
- ) -> None:
- self._resource = source_response
- self._source_cursor_manager = source_cursor_manager
- self._resource_name = source_response.name
-
- # Persisted PK (user override or earlier detection) > live-detected > `id` fallback. Keeps
- # the merge key stable across runs when live detection (e.g. Snowflake SHOW PRIMARY KEYS)
- # intermittently returns nothing.
- self._resource.primary_keys = resolve_primary_keys(models.schema, self._resource)
-
- self._job = models.job
- self._reset_pipeline = reset_pipeline
- self._logger = logger
- self._load_id = time.time_ns()
-
- self._schema = models.schema
- self._source = models.source
- self._table = models.table
- # xmin reads deltas and upserts on the primary key, so it writes incrementally too — never
- # as a full_refresh overwrite, which would wipe earlier data on the second (delta-only) sync.
- self._is_incremental = models.schema.is_incremental or models.schema.is_webhook or models.schema.is_xmin
-
- # Mirrors the `is_first_sync` passed to `validate_incremental_sync` below: a schema with no
- # `DataWarehouseTable` row yet is a fresh (or retried-fresh) sync even when a Delta table
- # already exists in storage from an earlier attempt at writing the same first sync. Without
- # this, the writer's own is-first-sync detection (no physical table found) never fires for
- # that case, and an incremental write with no primary key wrongly takes the merge path
- # instead of overwriting, raising MissingPrimaryKeysException on an otherwise-healthy sync.
- self._delta_table_ref = DeltaTableRef(
- self._resource_name, self._job, self._logger, is_first_sync=self._table is None
- )
- self._resumable_source_manager = resolve_resume_manager(resumable_source_manager, self._resource)
- # A source can shrink the batcher chunk (e.g. document sources with large rows) so the
- # source->Arrow conversion doesn't materialise an oversized table; None falls back to defaults.
- self._batcher = Batcher(
- self._logger,
- chunk_size=source_response.chunk_size,
- chunk_size_bytes=source_response.chunk_size_bytes,
- source_type=self._source.source_type,
- team_id=self._job.team_id,
- schema_name=self._schema.name,
- primary_keys=self._resource.primary_keys,
- )
- self._internal_schema = HogQLSchema()
- self._sinks = build_pipeline_sinks(
- team_id=self._job.team_id,
- schema_id=self._schema.id,
- job_id=job_id,
- logger=self._logger,
- is_incremental=self._is_incremental,
- )
- self._shutdown_monitor = shutdown_monitor
- self._last_incremental_field_value: Any = None
- self._earliest_incremental_field_value: Any = process_incremental_value(
- models.schema.incremental_field_earliest_value, models.schema.incremental_field_type
- )
- # SQL sources project enabled_columns in their SELECT and own schema_metadata via
- # introspection; managed-schema sources don't allow selection. Everything else gets the
- # Delta-write-side drop plus observed-columns capture so the column picker has a catalog.
- self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(models.source.source_type)
- self._observed_columns: dict[str, dict[str, Any]] = {}
-
- def _activate_safe_point(self, items: Any) -> contextlib.ExitStack:
- scope = contextlib.ExitStack()
- if self._resumable_source_manager is not None:
- handler = PipelineSafePointHandler(
- shutdown_monitor=self._shutdown_monitor,
- resumable_source_manager=self._resumable_source_manager,
- has_unwritten_rows=lambda: self._batcher.should_yield(include_incomplete_chunk=True),
- )
- scope.enter_context(
- activate_safe_point(handler, covers_framework_checkpoints=source_items_are_framework_output(items))
- )
- return scope
-
- async def _commit_resume_state(self) -> None:
- if self._resumable_source_manager is not None:
- await asyncio.to_thread(self._resumable_source_manager.commit)
-
- async def run(self) -> PipelineResult:
- pa_memory_pool = pa.default_memory_pool()
-
- should_resume = self._resumable_source_manager is not None and self._resumable_source_manager.can_resume()
- source_is_resumable = self._resumable_source_manager is not None
- if should_resume:
- await self._logger.ainfo("Resumable source detected - attempting to resume previous import")
-
- try:
- await self._sinks.clear()
-
- await reset_rows_synced_if_needed(self._job, self._is_incremental, self._reset_pipeline, should_resume)
-
- validate_incremental_sync(
- self._is_incremental,
- self._resource,
- is_first_sync=self._table is None or self._reset_pipeline,
- )
-
- await persist_primary_keys(self._schema, self._resource, self._is_incremental, self._logger)
-
- await setup_row_tracking_with_billing_check(
- self._job.team_id,
- self._schema,
- self._resource,
- self._source,
- self._logger,
- billable=self._job.billable,
- )
-
- py_table = None
- row_count = 0
- chunk_index = 0
-
- # Revive a corrupt-`_delta_log` table (from an interrupted repartition swap or OOM-crashed
- # merge) before extraction so it self-heals in this run instead of looping forever.
- await handle_corrupted_delta_log(self._schema, self._job, self._delta_table_ref, self._logger)
-
- await handle_reset_or_full_refresh(
- self._reset_pipeline,
- should_resume,
- self._schema,
- self._delta_table_ref,
- self._logger,
- webhook_only=self._resource.webhook_only,
- )
-
- # If the schema has no DWH table, it's a first ever sync
- is_first_ever_sync: bool = self._table is None
-
- # Defensive pre-write compaction so a sync that arrived at a fragmented
- # Delta target (e.g. earlier attempts that failed before reaching
- # `_post_run_operations`) cleans up before adding more small files. Skipped
- # cheaply when the table is healthy; see DeltaMaintenance.run_scheduled.
- if not is_first_ever_sync:
- await DeltaMaintenance(self._delta_table_ref).run_scheduled(self._schema)
-
- async def write_remaining_rows() -> None:
- nonlocal chunk_index, row_count
- while self._batcher.should_yield(include_incomplete_chunk=True):
- py_table = self._batcher.get_table()
- row_count += py_table.num_rows
- await self._process_pa_table(
- pa_table=py_table,
- index=chunk_index,
- resuming_sync=should_resume,
- row_count=row_count,
- is_first_ever_sync=is_first_ever_sync,
- )
- chunk_index += 1
- # Every yielded row is written now, so whatever the source staged last is safe.
- await self._commit_resume_state()
-
- items = self._resource.items()
- safe_point_scope = self._activate_safe_point(items)
- awaiting_source = True
- try:
- async for item in async_iterate(items):
- awaiting_source = False
- py_table = None
-
- record_source_item_stats(
- item,
- source_type=self._source.source_type,
- logger=self._logger,
- team_id=self._job.team_id,
- schema_name=self._schema.name,
- )
-
- self._batcher.batch(item)
-
- # A single batched table may be split into several when a string/binary/list
- # column would otherwise overflow a 32-bit offset, so drain every ready chunk.
- wrote_chunk = False
- while self._batcher.should_yield():
- py_table = self._batcher.get_table()
-
- row_count += py_table.num_rows
-
- await self._process_pa_table(
- pa_table=py_table,
- index=chunk_index,
- resuming_sync=should_resume,
- row_count=row_count,
- is_first_ever_sync=is_first_ever_sync,
- )
- wrote_chunk = True
-
- chunk_index += 1
-
- cleanup_memory(pa_memory_pool, py_table)
- py_table = None
-
- # A write is what makes the staged cursor safe to persist: after a buffered-only item
- # it would skip rows that never landed, and after the shutdown check it would never land.
- if wrote_chunk:
- await self._commit_resume_state()
-
- if should_check_shutdown(self._schema, self._resource, self._reset_pipeline, source_is_resumable):
- self._shutdown_monitor.raise_if_is_worker_shutdown()
- awaiting_source = True
- except Exception:
- # A resumable source that ends its own attempt (a page or time budget) has staged a
- # cursor for rows the batcher still holds. Writing them lets that cursor commit, so the
- # next attempt continues from it instead of restarting the sweep.
- if awaiting_source and source_is_resumable:
- try:
- await write_remaining_rows()
- except Exception:
- await self._logger.aexception("Failed to write the rows buffered before the source error")
- raise
- finally:
- safe_point_scope.close()
-
- await write_remaining_rows()
- await self._persist_observed_columns()
-
- prepared_queryable_folder = await self._post_run_operations(row_count=row_count)
-
- await commit_source_cursor(self._source_cursor_manager, self._schema, self._logger, staging_run_uuid=None)
-
- result = PipelineResult(should_trigger_cdp_producer=await self._sinks.cdp_producer.should_run())
- if isinstance(prepared_queryable_folder, str):
- result["prepared_queryable_folder"] = prepared_queryable_folder
- if self._resource.on_complete is not None:
- try:
- await asyncio.to_thread(self._resource.on_complete)
- except Exception:
- await self._logger.aexception("Failed to clean up completed source state")
- return result
- finally:
- # Help reduce the memory footprint of each job. This is best-effort cleanup of
- # whatever `get_delta_table` already cached this run — pop rather than call, so a
- # run that failed before ever fetching the delta table (nothing to release) doesn't
- # make a fresh, unrelated object-storage call here that can itself raise and get
- # captured, obscuring the real import error that's already driving retry
- # classification and the user-facing message.
- await self._logger.adebug("Cleaning up delta table helper")
- delta_table = self._delta_table_ref.pop_cached_table()
- if delta_table:
- del delta_table
-
- del self._resource
- del self._delta_table_ref
-
- cleanup_memory(pa_memory_pool, py_table if "py_table" in locals() else None)
-
- async def _persist_observed_columns(self) -> None:
- """Union the columns the source actually returned into `schema_metadata["columns"]`.
-
- Bookkeeping for the column picker — a failure here must not fail an otherwise
- successful sync.
- """
- if not self._observed_columns:
- return
- observed = list(self._observed_columns.values())
- try:
- await database_sync_to_async_pool(update_sync_type_config_keys)(
- self._schema.id,
- self._job.team_id,
- mutate=lambda config: merge_observed_columns_into_schema_metadata(config, observed),
- )
- except Exception:
- await self._logger.aexception("Failed to persist observed columns into schema_metadata")
-
- async def _process_pa_table(
- self, pa_table: pa.Table, index: int, resuming_sync: bool, row_count: int, is_first_ever_sync: bool
- ):
- delta_table = await self._delta_table_ref.get_delta_table()
- previous_file_uris = await self._delta_table_ref.get_file_uris()
-
- pa_table = _append_debug_column_to_pyarrows_table(pa_table, self._load_id)
- pa_table = normalize_table_column_names(pa_table)
-
- if self._uses_delta_write_column_selection:
- pa_table = await observe_and_project_table(
- pa_table,
- self._schema.enabled_columns,
- self._resource.primary_keys,
- self._schema.incremental_field,
- [
- *(self._schema.partitioning_keys_override or []),
- *(self._schema.partitioning_keys or []),
- *(self._resource.partition_keys or []),
- ],
- self._observed_columns,
- self._logger,
- "Dropped non-enabled columns before Delta write",
- )
-
- pa_table = await setup_partitioning(pa_table, delta_table, self._schema, self._resource, self._logger)
-
- pa_table = evolve_pyarrow_schema(
- pa_table,
- delta_table.schema() if delta_table is not None else None,
- merge_key_columns=[
- *(self._resource.primary_keys or []),
- *(self._schema.partitioning_keys_override or []),
- *(self._schema.partitioning_keys or []),
- *(self._resource.partition_keys or []),
- ],
- )
- pa_table = _handle_null_columns_with_definitions(pa_table, self._resource)
-
- write_type: Literal["incremental", "full_refresh", "append"] = "full_refresh"
- if self._schema.is_incremental or self._schema.is_webhook or self._schema.is_xmin:
- write_type = "incremental"
- elif self._schema.is_append:
- write_type = "append"
-
- should_overwrite_table = index == 0 and not resuming_sync
-
- delta_table = await DeltaWriter(self._delta_table_ref).write(
- pa_table,
- write_type,
- should_overwrite_table=should_overwrite_table,
- primary_keys=self._resource.primary_keys,
- )
-
- self._internal_schema.add_pyarrow_table(pa_table)
-
- await self._sinks.stage_chunk(index, pa_table)
-
- incremental_values = await update_incremental_field_values(
- self._schema,
- pa_table,
- self._resource,
- self._last_incremental_field_value,
- self._earliest_incremental_field_value,
- self._logger,
- )
- self._last_incremental_field_value = incremental_values.last_value
- self._earliest_incremental_field_value = incremental_values.earliest_value
-
- await update_row_tracking_after_batch(
- self._job.id, self._job.team_id, self._schema.id, pa_table.num_rows, self._logger
- )
-
- # if it's the first ever sync for this schema and the source supports partial data loading, we make the delta
- # table files available for querying and create the data warehouse table, so that the user has some data
- # available to start using
- # TODO - enable this for all source types
- if is_first_ever_sync and supports_partial_data_loading(self._schema):
- file_uris = await self._delta_table_ref.get_file_uris()
-
- await self._process_partial_data(
- previous_file_uris=previous_file_uris,
- file_uris=file_uris,
- row_count=row_count,
- chunk_index=index,
- )
-
- async def _process_partial_data(
- self, previous_file_uris: list[str], file_uris: list[str], row_count: int, chunk_index: int
- ):
- await self._logger.adebug(
- "Source supports partial data loading and is first ever sync -> "
- "making delta table files available for querying and creating data warehouse table"
- )
- if chunk_index == 0:
- new_file_uris = file_uris
- else:
- new_file_uris = list(set(file_uris) - set(previous_file_uris))
- # in theory, we should always be appending files for a first time sync but we just check that this is the
- # case in case we update this assumption
- files_modified = set(previous_file_uris) - set(file_uris)
- if len(files_modified) > 0:
- await self._logger.awarning(
- "Should always be appending delta table files for a first time sync but found modified files!"
- )
- capture_exception(
- Exception(
- "Should always be appending delta table files for a first time sync but found modified files!"
- )
- )
- return
-
- await self._logger.adebug(f"Adding {len(new_file_uris)} S3 files to query folder")
- folder_path = await database_sync_to_async_pool(self._job.folder_path)()
- queryable_folder = await prepare_s3_files_for_querying(
- folder_path=folder_path,
- table_name=self._resource_name,
- file_uris=new_file_uris,
- # delete existing files if it's the first chunk, otherwise we'll just append to the existing files
- delete_existing=chunk_index == 0,
- use_timestamped_folders=False,
- logger=self._logger,
- )
- await self._logger.adebug("Validating schema and updating table")
- await validate_schema_and_update_table(
- run_id=str(self._job.id),
- team_id=self._job.team_id,
- schema_id=self._schema.id,
- table_schema_dict=self._internal_schema.to_hogql_types(),
- row_count=row_count,
- queryable_folder=queryable_folder,
- table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
- )
-
- async def _post_run_operations(self, row_count: int) -> str | None:
- return await run_post_load_operations(
- job=self._job,
- schema=self._schema,
- source=self._source,
- delta_table_ref=self._delta_table_ref,
- row_count=row_count,
- table_schema_dict=self._internal_schema.to_hogql_types(),
- resource_name=self._resource_name,
- logger=self._logger,
- last_incremental_field_value=self._last_incremental_field_value,
- resource=self._resource,
- allow_zero_row_skip=True,
- )
-
-
-def _estimate_size(obj: Any) -> int:
- if isinstance(obj, dict):
- return sys.getsizeof(obj) + sum(_estimate_size(k) + _estimate_size(v) for k, v in obj.items())
- elif isinstance(obj, list | tuple | set):
- return sys.getsizeof(obj) + sum(_estimate_size(i) for i in obj)
- else:
- return sys.getsizeof(obj)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
deleted file mode 100644
index 00c8f2edd07a..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
+++ /dev/null
@@ -1,289 +0,0 @@
-import json
-import uuid
-from contextlib import ExitStack, nullcontext
-from dataclasses import dataclass
-from types import SimpleNamespace
-from typing import cast
-
-import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pyarrow as pa
-from parameterized import parameterized
-
-from posthog.temporal.common.shutdown import WorkerShuttingDownError
-
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLT
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
- ImportJobModels,
-)
-
-_PIPELINE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline"
-
-
-async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_import_error():
- # Regression: run()'s finally used to call get_delta_table() (object-storage I/O) purely for
- # memory cleanup, even on a run that failed before ever fetching a delta table (nothing
- # cached, nothing to clean up). A transient object-storage blip on that spurious call then
- # replaced the in-flight import error, so a failure already classified as non-retryable
- # surfaced as the unrelated cleanup error and the job retried to its maximum instead of
- # stopping. Cleanup must pop whatever's cached instead of recomputing it, so it can no
- # longer make its own object-storage call at all.
- pipeline = PipelineNonDLT.__new__(PipelineNonDLT)
- pipeline._logger = AsyncMock()
- pipeline._resumable_source_manager = None
- pipeline._resource = cast(SourceResponse, object())
- delta_table_ref = AsyncMock()
- delta_table_ref.pop_cached_table.return_value = None
- pipeline._delta_table_ref = delta_table_ref
-
- class ImportError_(Exception):
- pass
-
- pipeline._sinks = MagicMock(clear=AsyncMock(side_effect=ImportError_("Can't connect to MySQL server on")))
-
- with pytest.raises(ImportError_, match="Can't connect to MySQL server on"):
- await pipeline.run()
-
- # run()'s finally `del self._delta_table_ref`s afterward, so assert on the captured
- # reference rather than re-reading it off `pipeline`.
- delta_table_ref.get_delta_table.assert_not_called()
- delta_table_ref.pop_cached_table.assert_called_once_with()
-
-
-async def test_post_run_operations_routes_through_shared_post_load():
- # The e2e tests mock `_post_run_operations`, so nothing else notices if this wrapper stops
- # returning the orchestrator's queryable folder (ducklake registration silently loses
- # `prepared_queryable_folder`) or stops forwarding the resource and last incremental value
- # (desc-sort cursor finalization silently skips).
- pipeline = PipelineNonDLT.__new__(PipelineNonDLT)
- pipeline._logger = AsyncMock()
- pipeline._delta_table_ref = AsyncMock()
- pipeline._job = MagicMock(id=uuid.uuid4(), team_id=1)
- pipeline._resource_name = "orders"
- pipeline._schema = MagicMock()
- pipeline._source = MagicMock()
- pipeline._resource = MagicMock()
- pipeline._internal_schema = MagicMock()
- pipeline._last_incremental_field_value = 5
-
- post_load = AsyncMock(return_value="orders__query_2")
- with patch(f"{_PIPELINE_MODULE}.run_post_load_operations", post_load):
- result = await pipeline._post_run_operations(row_count=10)
-
- assert result == "orders__query_2"
- assert post_load.await_args is not None
- kwargs = post_load.await_args.kwargs
- assert kwargs["resource"] is pipeline._resource
- assert kwargs["last_incremental_field_value"] == 5
- assert kwargs["row_count"] == 10
-
-
-class TestDeltaTableRefFirstSyncWiring:
- @parameterized.expand(
- [
- ("no_table_row_yet", None, True),
- ("table_row_already_exists", MagicMock(), False),
- ]
- )
- def test_is_first_sync_matches_whether_a_table_row_exists(
- self, _name: str, table: MagicMock | None, expected_is_first_sync: bool
- ) -> None:
- # Regression: a schema with no DataWarehouseTable row yet is treated as a first sync by
- # `validate_incremental_sync` (which skips the primary-key requirement), but the writer's
- # own first-sync detection only fires when no Delta table physically exists in storage.
- # If a Delta table happens to already exist there (e.g. left over from an earlier attempt
- # at this same first sync), those two checks used to disagree and the writer wrongly took
- # the merge path, raising MissingPrimaryKeysException on a keyless incremental table that
- # `validate_incremental_sync` had just waved through. The `DeltaTableRef` must be
- # constructed with `is_first_sync` set from the same `table is None` check.
- mock_job = MagicMock(team_id=1)
- mock_schema = MagicMock(
- id="schema-1",
- name="orders",
- is_incremental=True,
- is_webhook=False,
- is_xmin=False,
- incremental_field_earliest_value=None,
- incremental_field_type=None,
- )
- mock_source = MagicMock(source_type="Redshift")
- mock_resource = MagicMock(name="orders", chunk_size=None, chunk_size_bytes=None)
-
- with (
- patch(f"{_PIPELINE_MODULE}.resolve_primary_keys", return_value=None),
- patch(f"{_PIPELINE_MODULE}.Batcher"),
- patch(f"{_PIPELINE_MODULE}.HogQLSchema"),
- patch(f"{_PIPELINE_MODULE}.build_pipeline_sinks"),
- patch(f"{_PIPELINE_MODULE}.source_uses_delta_write_column_selection", return_value=False),
- patch(f"{_PIPELINE_MODULE}.DeltaTableRef") as mock_delta_table_ref_cls,
- ):
- PipelineNonDLT(
- source_response=mock_resource,
- logger=MagicMock(),
- job_id="job-1",
- reset_pipeline=False,
- shutdown_monitor=MagicMock(),
- resumable_source_manager=None,
- models=ImportJobModels(job=mock_job, schema=mock_schema, source=mock_source, table=table),
- )
-
- assert mock_delta_table_ref_cls.call_args.kwargs["is_first_sync"] is expected_is_first_sync
-
-
-@dataclass(frozen=True)
-class _Cursor:
- id: str
-
-
-def _manager() -> ResumableSourceManager[_Cursor]:
- inputs = cast(SourceInputs, SimpleNamespace(team_id=1, job_id="job-1", logger=MagicMock()))
- return ResumableSourceManager[_Cursor](inputs, _Cursor)
-
-
-def _table_source(manager: ResumableSourceManager[_Cursor], ids: list[str], stage_before_yield: bool):
- def items():
- previous = None
- for row_id in ids:
- if stage_before_yield:
- manager.save_state(_Cursor(row_id))
- elif previous is not None:
- manager.save_state(_Cursor(previous))
- yield pa.table({"id": [row_id]})
- previous = row_id
-
- return items
-
-
-def _runnable_pipeline(manager: ResumableSourceManager[_Cursor], items) -> PipelineNonDLT:
- pipeline = PipelineNonDLT.__new__(PipelineNonDLT)
- logger = MagicMock()
- logger.adebug = AsyncMock()
- logger.ainfo = AsyncMock()
- logger.awarning = AsyncMock()
- logger.aexception = AsyncMock()
- pipeline._logger = logger
- pipeline._resumable_source_manager = manager
- pipeline._resource = SourceResponse(name="orders", items=items, primary_keys=["id"])
- pipeline._batcher = Batcher(MagicMock(), primary_keys=["id"])
- pipeline._schema = MagicMock(should_use_incremental_field=False)
- pipeline._source = MagicMock(source_type="Stripe")
- pipeline._job = MagicMock(team_id=1, billable=False)
- pipeline._table = None
- pipeline._is_incremental = False
- pipeline._reset_pipeline = False
- delta_table_ref = AsyncMock()
- delta_table_ref.pop_cached_table.return_value = None
- pipeline._delta_table_ref = delta_table_ref
- pipeline._sinks = MagicMock(clear=AsyncMock())
- pipeline._shutdown_monitor = MagicMock()
- pipeline._process_pa_table = AsyncMock() # type: ignore[method-assign]
- return pipeline
-
-
-def _raise_on_second_call(exc: Exception):
- calls = {"n": 0}
-
- def side_effect():
- calls["n"] += 1
- if calls["n"] == 2:
- raise exc
-
- return side_effect
-
-
-def _run_patches():
- return (
- patch(f"{_PIPELINE_MODULE}.reset_rows_synced_if_needed", new_callable=AsyncMock),
- patch(f"{_PIPELINE_MODULE}.validate_incremental_sync"),
- patch(f"{_PIPELINE_MODULE}.persist_primary_keys", new_callable=AsyncMock),
- patch(f"{_PIPELINE_MODULE}.setup_row_tracking_with_billing_check", new_callable=AsyncMock),
- patch(f"{_PIPELINE_MODULE}.handle_corrupted_delta_log", new_callable=AsyncMock),
- patch(f"{_PIPELINE_MODULE}.handle_reset_or_full_refresh", new_callable=AsyncMock),
- patch(f"{_PIPELINE_MODULE}.record_source_item_stats"),
- )
-
-
-class TestResumeCursorCommit:
- @parameterized.expand(
- [
- ("staged_before_yield", True, ["a", "b"]),
- ("staged_after_yield", False, ["a"]),
- ]
- )
- @pytest.mark.asyncio
- async def test_cursor_persisted_covers_exactly_the_written_chunks(
- self, _name: str, stage_before_yield: bool, expected_committed: list[str]
- ) -> None:
- redis = MagicMock()
- manager = _manager()
- pipeline = _runnable_pipeline(manager, _table_source(manager, ["a", "b", "c"], stage_before_yield))
- shutdown = WorkerShuttingDownError("id", "type", "queue", 1, "workflow", "workflow_type")
- cast(MagicMock, pipeline._shutdown_monitor).raise_if_is_worker_shutdown.side_effect = _raise_on_second_call(
- shutdown
- )
-
- with ExitStack() as stack:
- stack.enter_context(patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)))
- for run_patch in _run_patches():
- stack.enter_context(run_patch)
- with pytest.raises(WorkerShuttingDownError):
- await pipeline.run()
-
- assert cast(AsyncMock, pipeline._process_pa_table).await_count == 2
- assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == expected_committed
-
- @pytest.mark.asyncio
- async def test_cursor_not_persisted_for_rows_the_batcher_still_holds(self) -> None:
- redis = MagicMock()
- manager = _manager()
-
- def items():
- yield [{"id": "a"}]
- manager.save_state(_Cursor("a"))
- yield [{"id": "b"}]
- manager.save_state(_Cursor("b"))
- yield [{"id": "c"}]
-
- pipeline = _runnable_pipeline(manager, items)
- shutdown = WorkerShuttingDownError("id", "type", "queue", 1, "workflow", "workflow_type")
- cast(MagicMock, pipeline._shutdown_monitor).raise_if_is_worker_shutdown.side_effect = _raise_on_second_call(
- shutdown
- )
-
- with ExitStack() as stack:
- stack.enter_context(patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)))
- for run_patch in _run_patches():
- stack.enter_context(run_patch)
- with pytest.raises(WorkerShuttingDownError):
- await pipeline.run()
-
- cast(AsyncMock, pipeline._process_pa_table).assert_not_awaited()
- redis.set.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_rows_buffered_when_the_source_raises_are_written_with_their_cursor(self) -> None:
- redis = MagicMock()
- manager = _manager()
-
- def items():
- manager.save_state(_Cursor("a"))
- yield [{"id": "a"}]
- raise RuntimeError("page budget")
-
- pipeline = _runnable_pipeline(manager, items)
-
- with ExitStack() as stack:
- stack.enter_context(patch.object(ResumableSourceManager, "_get_redis", lambda self: nullcontext(redis)))
- for run_patch in _run_patches():
- stack.enter_context(run_patch)
- with pytest.raises(RuntimeError):
- await pipeline.run()
-
- assert cast(AsyncMock, pipeline._process_pa_table).await_count == 1
- assert [json.loads(call.args[1])["id"] for call in redis.set.call_args_list] == ["a"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index f736bc59cceb..402cf7454011 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -420,13 +420,7 @@ class PipelineV3(Generic[ResumableData]):
# v3 stages the incremental cursor until job completion, so a retried attempt
# re-extracts from batch 0 and the previous attempt's count must not be kept.
- await reset_rows_synced_if_needed(
- self._job,
- self._is_incremental,
- self._reset_pipeline,
- should_resume,
- incremental_cursor_staged=True,
- )
+ await reset_rows_synced_if_needed(self._job, should_resume)
validate_incremental_sync(
self._is_incremental,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index 6884f689094f..fcb47509dfcc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -1942,18 +1942,7 @@ class PostgresSource(
supports_resume=False,
)
- # Defense in depth for the v3-forcing invariant: a run that resolved its pipeline version
- # before its table started streaming, or a worker one deploy behind, would consume this
- # buffer on v2, which stamps no position on the rows it writes, so every later run would
- # find nothing to resume from and re-merge the whole buffer. Fail the run loudly instead of
- # degrading silently.
job = ExternalDataJob.objects.filter(id=inputs.job_id, team_id=inputs.team_id).first()
- if job is not None and job.pipeline_version != ExternalDataJob.PipelineVersion.V3:
- raise ValueError(
- f"Buffered CDC schema {schema.name} reached a {job.pipeline_version} pipeline run. "
- "Buffered consumption requires v3, whose loader stamps each row with the position "
- "the next run resumes from."
- )
# A CDC reset must travel through snapshot mode, which re-seeds the table before the buffer
# replays over it; every reset writer does that. Merging the buffer into a wiped table
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
index 81e44f22500f..d2ea5581f063 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
@@ -39,6 +39,12 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_job
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
from products.warehouse_sources.backend.temporal.data_imports.post_import_job import PostImportWorkflow
from products.warehouse_sources.backend.temporal.data_imports.settings import ACTIVITIES
+from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.queue_replay import (
+ PostgresQueueReplay,
+ ensure_queue_tables_in_test_database,
+ patch_producer_to_test_database,
+ replay_v3_consumer,
+)
from products.warehouse_sources_queue.backend.core.jobs_db import BATCH_TABLE, STATUS_TABLE
from products.warehouse_sources_queue.backend.testing import (
ensure_queue_tables as _ensure_tables,
@@ -176,6 +182,9 @@ async def run_external_data_job_workflow(
DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",
+ DATA_WAREHOUSE_REDIS_HOST="localhost",
+ DATA_WAREHOUSE_REDIS_PORT="6379",
+ DATAWAREHOUSE_BUCKET=BUCKET_NAME,
),
mock.patch.object(DeltaMaintenance, "run_scheduled") as mock_run_scheduled,
mock.patch(
@@ -183,7 +192,9 @@ async def run_external_data_job_workflow(
) as mock_get_data_import_finished_metric,
# make sure intended error of line 175 in posthog/warehouse/models/table.py doesn't trigger flag calls
mock.patch("posthoganalytics.capture_exception", return_value=None),
+ patch_producer_to_test_database(),
):
+ await sync_to_async(ensure_queue_tables_in_test_database)()
async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
async with Worker(
activity_environment.client,
@@ -212,6 +223,8 @@ async def run_external_data_job_workflow(
retry_policy=RetryPolicy(maximum_attempts=1),
)
+ await replay_v3_consumer(PostgresQueueReplay(), team.id, external_data_schema.id, BUCKET_NAME)
+
run = await get_latest_run_if_exists(team_id=team.pk, pipeline_id=external_data_source.pk)
assert run is not None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/queue_replay.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/queue_replay.py
new file mode 100644
index 000000000000..91f95f1d22eb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/queue_replay.py
@@ -0,0 +1,179 @@
+"""Test stand-in for the V3 load consumer.
+
+A V3 run only extracts: it writes batches to S3 and queue rows to the Postgres batch table, and
+the load consumer loads them later. Tests point the producer at the Django test database, then
+replay the queue rows through the consumer's `process_message` so the run finishes in-process.
+"""
+
+import json
+from typing import Any
+
+from unittest import mock
+
+from django.conf import settings
+from django.db import connection as django_conn
+from django.test import override_settings
+
+import psycopg
+from asgiref.sync import sync_to_async
+
+from products.warehouse_sources.backend.facade.models import ExternalDataJob
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (
+ process_message,
+)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (
+ CalculateTableSizeActivityInputs,
+ calculate_table_size_activity,
+)
+from products.warehouse_sources.backend.types import ExternalDataJobStatus
+from products.warehouse_sources_queue.backend.core.jobs_db import BATCH_TABLE, PendingBatch
+from products.warehouse_sources_queue.backend.testing import ensure_queue_tables, get_test_database_url
+
+PRODUCER_DATABASE_URL_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline."
+ "WAREHOUSE_SOURCES_DATABASE_URL"
+)
+
+
+class PostgresQueueReplay:
+ """Reads batch rows written by PostgresProducer during tests and replays them
+ through process_message(), mimicking what the real BatchConsumer does."""
+
+ def __init__(self) -> None:
+ self._processed_batches: set[tuple[str, int, str | None]] = set()
+
+ def replay_batches_for_run(self, run_uuid: str) -> None:
+ with django_conn.cursor() as cur:
+ cur.execute(
+ f"""
+ SELECT id, team_id, schema_id, source_id, job_id, run_uuid,
+ batch_index, s3_path, row_count, byte_size, is_final_batch,
+ total_batches, total_rows, sync_type, cumulative_row_count,
+ resource_name, is_resume, is_first_ever_sync, metadata, destination_ids
+ FROM {BATCH_TABLE}
+ WHERE run_uuid = %s
+ ORDER BY created_at ASC, batch_index ASC
+ """,
+ [run_uuid],
+ )
+ columns = [col.name for col in cur.description]
+ rows = [dict(zip(columns, row)) for row in cur.fetchall()]
+
+ if not rows:
+ return
+
+ for row in rows:
+ if isinstance(row.get("metadata"), str):
+ row["metadata"] = json.loads(row["metadata"])
+ # Same treatment as metadata: this cursor hands jsonb back as text, and iterating
+ # the string would feed "[" to the destination lookup as if it were an id.
+ if isinstance(row.get("destination_ids"), str):
+ row["destination_ids"] = json.loads(row["destination_ids"])
+ batch = PendingBatch(latest_attempt=0, **row)
+ try:
+ process_message(batch.to_export_signal())
+ except Exception:
+ pass
+
+ def get_run_uuids_for_job(self, job_id: str) -> list[str]:
+ with django_conn.cursor() as cur:
+ cur.execute(
+ f"SELECT DISTINCT run_uuid FROM {BATCH_TABLE} WHERE job_id = %s ORDER BY run_uuid",
+ [job_id],
+ )
+ return [row[0] for row in cur.fetchall()]
+
+ def mock_idempotency_check(
+ self,
+ team_id: int,
+ schema_id: str,
+ run_uuid: str,
+ 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)
+ if key in self._processed_batches:
+ return True
+ self._processed_batches.add(key)
+ return False
+
+ def clear(self) -> None:
+ self._processed_batches.clear()
+
+
+def ensure_queue_tables_in_test_database() -> None:
+ with psycopg.connect(get_test_database_url(), autocommit=True) as conn:
+ ensure_queue_tables(conn)
+
+
+def patch_producer_to_test_database() -> Any:
+ return mock.patch(PRODUCER_DATABASE_URL_PATH, get_test_database_url())
+
+
+async def replay_v3_consumer(
+ replay: PostgresQueueReplay,
+ team_id: int,
+ schema_id: Any,
+ bucket_name: str,
+ job_id: str | None = None,
+) -> None:
+ if not job_id:
+ job = await sync_to_async(
+ ExternalDataJob.objects.filter(team_id=team_id, schema_id=schema_id).order_by("-created_at").first
+ )()
+ if not job:
+ return
+ job_id = str(job.id)
+ else:
+ job = await sync_to_async(ExternalDataJob.objects.get)(id=job_id)
+
+ # If the workflow already marked the job as COMPLETED (e.g. worker shutdown scenario),
+ # the consumer should not replay — the workflow managed the job status itself and
+ # S3 files may have been cleaned up.
+ if job.status == ExternalDataJobStatus.COMPLETED:
+ replay.clear()
+ return
+
+ run_uuids = await sync_to_async(replay.get_run_uuids_for_job)(job_id)
+ if not run_uuids:
+ replay.clear()
+ return
+
+ with (
+ override_settings(
+ BUCKET_URL=f"s3://{bucket_name}",
+ BUCKET_PATH=bucket_name,
+ DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
+ DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
+ DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
+ DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",
+ DATA_WAREHOUSE_REDIS_HOST="localhost",
+ DATA_WAREHOUSE_REDIS_PORT="6379",
+ DATAWAREHOUSE_BUCKET=bucket_name,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.is_batch_already_processed",
+ side_effect=replay.mock_idempotency_check,
+ ),
+ ):
+ for run_uuid in run_uuids:
+ await sync_to_async(replay.replay_batches_for_run)(run_uuid)
+
+ await sync_to_async(calculate_table_size_activity)(
+ CalculateTableSizeActivityInputs(
+ team_id=team_id,
+ schema_id=str(schema_id),
+ job_id=job_id,
+ )
+ )
+
+ replay.clear()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_bigquery_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_bigquery_source.py
index 185b2d790779..abdb2ad26abc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_bigquery_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_bigquery_source.py
@@ -25,6 +25,12 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
)
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType, IncrementalFieldType
+from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.queue_replay import (
+ PostgresQueueReplay,
+ ensure_queue_tables_in_test_database,
+ patch_producer_to_test_database,
+ replay_v3_consumer,
+)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
ImportDataActivityInputs,
import_data_activity_sync,
@@ -315,11 +321,21 @@ async def setup_bigquery(
status=ExternalDataJob.Status.RUNNING,
rows_synced=0,
workflow_id="some_workflow_id",
- pipeline_version=ExternalDataJob.PipelineVersion.V1,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
)
return ImportDataActivityInputs(team_id=team.pk, schema_id=schema.pk, source_id=source.pk, run_id=str(job.pk))
+async def _import_and_load(activity_environment, inputs: ImportDataActivityInputs, bucket_name: str) -> None:
+ """Run the extraction, then replay the load queue the way the V3 load consumer would."""
+ # A finished job skips the replay, and the incremental tests run the same job twice.
+ await ExternalDataJob.objects.filter(id=inputs.run_id).aupdate(status=ExternalDataJob.Status.RUNNING)
+ await sync_to_async(ensure_queue_tables_in_test_database)()
+ with patch_producer_to_test_database():
+ await activity_environment.run(import_data_activity_sync, inputs)
+ await replay_v3_consumer(PostgresQueueReplay(), inputs.team_id, inputs.schema_id, bucket_name, job_id=inputs.run_id)
+
+
@SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS
@pytest.mark.django_db
@pytest.mark.asyncio
@@ -354,7 +370,7 @@ async def test_bigquery_source_full_refresh_table(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
@@ -420,7 +436,7 @@ async def test_bigquery_source_full_refresh_view(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
@@ -489,7 +505,7 @@ async def test_bigquery_source_incremental_integer(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
@@ -536,7 +552,7 @@ async def test_bigquery_source_incremental_integer(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
@@ -610,7 +626,7 @@ async def test_bigquery_source_incremental_timestamp(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
@@ -658,7 +674,7 @@ async def test_bigquery_source_incremental_timestamp(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
@@ -736,7 +752,7 @@ async def test_bigquery_source_incremental_custom_primary_key(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
@@ -784,7 +800,7 @@ async def test_bigquery_source_incremental_custom_primary_key(
BUCKET_URL=f"s3://{bucket_name}",
BUCKET_PATH=bucket_name,
):
- await activity_environment.run(import_data_activity_sync, inputs)
+ await _import_and_load(activity_environment, inputs, bucket_name)
objects = minio_client.list_objects_v2(Bucket=bucket_name, Prefix="")
assert objects.get("KeyCount", 0) > 0
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 2e2ea8d816ce..53573531345b 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
@@ -1,5 +1,4 @@
import re
-import json
import uuid
import functools
import contextlib
@@ -77,10 +76,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.con
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
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.pipeline_v2.pipeline import PipelineNonDLT
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (
- process_message,
-)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
from products.warehouse_sources.backend.temporal.data_imports.post_import_job import (
PostImportWorkflow,
@@ -118,9 +113,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.con
SUBSCRIPTION_RESOURCE_NAME as STRIPE_SUBSCRIPTION_RESOURCE_NAME,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import InvoiceListWithAllLines
-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (
- CalculateTableSizeActivityInputs,
- calculate_table_size_activity,
+from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.queue_replay import (
+ PostgresQueueReplay,
+ replay_v3_consumer,
)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.sync_new_schemas import (
ExternalDataSourceType,
@@ -133,21 +128,15 @@ from products.warehouse_sources.backend.types import (
ExternalDataSchemaSyncType,
IncrementalSyncBlockedReason,
)
-from products.warehouse_sources_queue.backend.core.jobs_db import BATCH_TABLE, PendingBatch
BUCKET_NAME = "test-pipeline"
SESSION = aioboto3.Session()
create_test_client = functools.partial(SESSION.client, endpoint_url=settings.OBJECT_STORAGE_ENDPOINT)
-_current_pipeline_mode = "non_dlt"
-
[email protected](params=["non_dlt", "v3"], autouse=True)
-def pipeline_mode(request, _clean_sourcebatch_tables):
- global _current_pipeline_mode
- _current_pipeline_mode = request.param
- yield request.param
- _current_pipeline_mode = "non_dlt"
[email protected](autouse=True)
+def _clean_tables_for_every_test(_clean_sourcebatch_tables):
+ yield
def _get_test_database_url() -> str:
@@ -160,86 +149,7 @@ def _get_test_database_url() -> str:
return f"postgres://{s['USER']}:{s['PASSWORD']}@{host}:{port}/{s['NAME']}"
-class _PostgresQueueReplay:
- """Reads batch rows written by PostgresProducer during tests and replays them
- through process_message(), mimicking what the real BatchConsumer does."""
-
- def __init__(self) -> None:
- self._processed_batches: set[tuple[str, int, str | None]] = set()
-
- def replay_batches_for_run(self, run_uuid: str) -> None:
- from django.db import connection as django_conn
-
- with django_conn.cursor() as cur:
- cur.execute(
- f"""
- SELECT id, team_id, schema_id, source_id, job_id, run_uuid,
- batch_index, s3_path, row_count, byte_size, is_final_batch,
- total_batches, total_rows, sync_type, cumulative_row_count,
- resource_name, is_resume, is_first_ever_sync, metadata, destination_ids
- FROM {BATCH_TABLE}
- WHERE run_uuid = %s
- ORDER BY created_at ASC, batch_index ASC
- """,
- [run_uuid],
- )
- columns = [col.name for col in cur.description]
- rows = [dict(zip(columns, row)) for row in cur.fetchall()]
-
- if not rows:
- return
-
- for row in rows:
- if isinstance(row.get("metadata"), str):
- row["metadata"] = json.loads(row["metadata"])
- # Same treatment as metadata: this cursor hands jsonb back as text, and iterating
- # the string would feed "[" to the destination lookup as if it were an id.
- if isinstance(row.get("destination_ids"), str):
- row["destination_ids"] = json.loads(row["destination_ids"])
- batch = PendingBatch(latest_attempt=0, **row)
- try:
- process_message(batch.to_export_signal())
- except Exception:
- pass
-
- def get_run_uuids_for_job(self, job_id: str) -> list[str]:
- from django.db import connection as django_conn
-
- with django_conn.cursor() as cur:
- cur.execute(
- f"SELECT DISTINCT run_uuid FROM {BATCH_TABLE} WHERE job_id = %s ORDER BY run_uuid",
- [job_id],
- )
- return [row[0] for row in cur.fetchall()]
-
- def mock_idempotency_check(
- self,
- team_id: int,
- schema_id: str,
- run_uuid: str,
- 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)
- if key in self._processed_batches:
- return True
- self._processed_batches.add(key)
- return False
-
- def clear(self) -> None:
- self._processed_batches.clear()
-
-
-_pg_queue_replay = _PostgresQueueReplay()
+_pg_queue_replay = PostgresQueueReplay()
@pytest.fixture
@@ -497,7 +407,7 @@ async def _run(
if existing_schema_id is not None:
# A genuine re-sync also runs the pre-write defensive maintenance pass (see
- # DeltaMaintenance.run_scheduled's callers in pipeline_v2/pipeline_v3), so both that call
+ # DeltaMaintenance.run_scheduled's callers in pipeline_v3), so both that call
# and the post-load call must land — asserting only "called" would still pass if the
# post-load call were dropped, since the pre-write call alone satisfies it.
assert mock_run_scheduled.call_count == 2
@@ -509,8 +419,7 @@ async def _run(
# Assert that app_metrics2 rows were emitted for the successful job — both
# the success row and the rows_synced row (since a successful e2e run writes
- # at least one row). Pin both V3 (consumer-side) and NonDLT (workflow-side)
- # paths so a regression in either gates here.
+ # at least one row). These come from the load consumer.
assert run.rows_synced is not None and run.rows_synced > 0, (
f"expected run.rows_synced to be a positive number, got {run.rows_synced}"
)
@@ -581,60 +490,7 @@ async def _run(
async def _replay_v3_consumer(team_id: int, schema_id, job_id: str | None = None):
- if _current_pipeline_mode != "v3":
- return
-
- if not job_id:
- job = await sync_to_async(
- ExternalDataJob.objects.filter(team_id=team_id, schema_id=schema_id).order_by("-created_at").first
- )()
- if not job:
- return
- job_id = str(job.id)
- else:
- job = await sync_to_async(ExternalDataJob.objects.get)(id=job_id)
-
- # If the workflow already marked the job as COMPLETED (e.g. worker shutdown scenario),
- # the consumer should not replay — the workflow managed the job status itself and
- # S3 files may have been cleaned up.
- if job.status == ExternalDataJobStatus.COMPLETED:
- _pg_queue_replay.clear()
- return
-
- run_uuids = await sync_to_async(_pg_queue_replay.get_run_uuids_for_job)(job_id)
- if not run_uuids:
- _pg_queue_replay.clear()
- return
-
- with (
- override_settings(
- BUCKET_URL=f"s3://{BUCKET_NAME}",
- BUCKET_PATH=BUCKET_NAME,
- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",
- DATA_WAREHOUSE_REDIS_HOST="localhost",
- DATA_WAREHOUSE_REDIS_PORT="6379",
- DATAWAREHOUSE_BUCKET=BUCKET_NAME,
- ),
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.is_batch_already_processed",
- side_effect=_pg_queue_replay.mock_idempotency_check,
- ),
- ):
- for run_uuid in run_uuids:
- await sync_to_async(_pg_queue_replay.replay_batches_for_run)(run_uuid)
-
- await sync_to_async(calculate_table_size_activity)(
- CalculateTableSizeActivityInputs(
- team_id=team_id,
- schema_id=str(schema_id),
- job_id=job_id,
- )
- )
-
- _pg_queue_replay.clear()
+ await replay_v3_consumer(_pg_queue_replay, team_id, schema_id, BUCKET_NAME, job_id=job_id)
async def _execute_workflow(
@@ -752,27 +608,13 @@ async def _execute_run(
mock.patch.object(AwsCredentials, "to_object_store_rs_credentials", mock_to_object_store_rs_credentials),
contextlib.ExitStack() as stack,
):
- if _current_pipeline_mode == "v3":
- stack.enter_context(
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock.is_pipeline_v3_enabled",
- return_value=True,
- )
- )
- # Point the Postgres producer at the Django test database
- stack.enter_context(
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.WAREHOUSE_SOURCES_DATABASE_URL",
- _get_test_database_url(),
- )
- )
- else:
- stack.enter_context(
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock.is_pipeline_v3_enabled",
- return_value=False,
- )
+ # Point the Postgres producer at the Django test database
+ stack.enter_context(
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.WAREHOUSE_SOURCES_DATABASE_URL",
+ _get_test_database_url(),
)
+ )
if activity_environment is not None:
await _execute_workflow(activity_environment, workflow_id, inputs)
@@ -1810,7 +1652,11 @@ async def test_billable_job(team, stripe_balance_transaction, mock_stripe_client
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_delta_no_merging_on_first_sync(team, postgres_config, postgres_connection, pipeline_mode):
+async def test_delta_no_merging_on_first_sync(
+ team,
+ postgres_config,
+ postgres_connection,
+):
await postgres_connection.execute(
"CREATE TABLE IF NOT EXISTS {schema}.test_table (id integer)".format(schema=postgres_config["schema"])
)
@@ -1836,7 +1682,6 @@ async def test_delta_no_merging_on_first_sync(team, postgres_config, postgres_co
),
mock.patch.object(DeltaTable, "merge") as mock_merge,
mock.patch.object(deltalake, "write_deltalake") as mock_write,
- mock.patch.object(PipelineNonDLT, "_post_run_operations") as mock_post_run_operations,
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.run_post_load_operations",
new_callable=AsyncMock,
@@ -1866,64 +1711,35 @@ async def test_delta_no_merging_on_first_sync(team, postgres_config, postgres_co
ignore_assertions=True,
)
- if pipeline_mode == "non_dlt":
- mock_post_run_operations.assert_called_once()
-
- mock_merge.assert_not_called()
- assert mock_write.call_count == 2
-
- _, first_call_kwargs = mock_write.call_args_list[0]
- _, second_call_kwargs = mock_write.call_args_list[1]
+ mock_v3_post_load.assert_called_once()
+ mock_merge.assert_not_called()
+ assert mock_write.call_count == 2
- assert first_call_kwargs == {
- "mode": "overwrite",
- "schema_mode": "overwrite",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
+ _, first_call_kwargs = mock_write.call_args_list[0]
+ _, second_call_kwargs = mock_write.call_args_list[1]
- assert second_call_kwargs == {
- "mode": "append",
- "schema_mode": "merge",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
- else:
- mock_v3_post_load.assert_called_once()
- mock_merge.assert_not_called()
- assert mock_write.call_count == 2
-
- _, first_call_kwargs = mock_write.call_args_list[0]
- _, second_call_kwargs = mock_write.call_args_list[1]
-
- assert first_call_kwargs == {
- "mode": "overwrite",
- "schema_mode": "overwrite",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
+ assert first_call_kwargs == {
+ "mode": "overwrite",
+ "schema_mode": "overwrite",
+ "table_or_uri": mock.ANY,
+ "data": mock.ANY,
+ "partition_by": mock.ANY,
+ "commit_properties": mock.ANY,
+ }
- assert second_call_kwargs == {
- "mode": "append",
- "schema_mode": "merge",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
+ assert second_call_kwargs == {
+ "mode": "append",
+ "schema_mode": "merge",
+ "table_or_uri": mock.ANY,
+ "data": mock.ANY,
+ "partition_by": mock.ANY,
+ "commit_properties": mock.ANY,
+ }
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_delta_no_merging_on_first_sync_uncapped_chunk_size(
- team, postgres_config, postgres_connection, pipeline_mode
-):
+async def test_delta_no_merging_on_first_sync_uncapped_chunk_size(team, postgres_config, postgres_connection):
await postgres_connection.execute(
"CREATE TABLE IF NOT EXISTS {schema}.test_table (id integer)".format(schema=postgres_config["schema"])
)
@@ -1946,7 +1762,6 @@ async def test_delta_no_merging_on_first_sync_uncapped_chunk_size(
),
mock.patch.object(DeltaTable, "merge") as mock_merge,
mock.patch.object(deltalake, "write_deltalake") as mock_write,
- mock.patch.object(PipelineNonDLT, "_post_run_operations") as mock_post_run_operations,
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.run_post_load_operations",
new_callable=AsyncMock,
@@ -1973,9 +1788,6 @@ async def test_delta_no_merging_on_first_sync_uncapped_chunk_size(
)
# With uncapped chunk size, all rows fit in 1 batch. Both modes: 1 write (overwrite), no merge.
- if pipeline_mode == "non_dlt":
- mock_post_run_operations.assert_called_once()
-
mock_merge.assert_not_called()
assert mock_write.call_count == 1
@@ -1993,7 +1805,11 @@ async def test_delta_no_merging_on_first_sync_uncapped_chunk_size(
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_delta_no_merging_on_first_sync_after_reset(team, postgres_config, postgres_connection, pipeline_mode):
+async def test_delta_no_merging_on_first_sync_after_reset(
+ team,
+ postgres_config,
+ postgres_connection,
+):
await postgres_connection.execute(
"CREATE TABLE IF NOT EXISTS {schema}.test_table (id integer)".format(schema=postgres_config["schema"])
)
@@ -2039,7 +1855,6 @@ async def test_delta_no_merging_on_first_sync_after_reset(team, postgres_config,
),
mock.patch.object(DeltaTable, "merge") as mock_merge,
mock.patch.object(deltalake, "write_deltalake") as mock_write,
- mock.patch.object(PipelineNonDLT, "_post_run_operations") as mock_post_run_operations,
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.run_post_load_operations",
new_callable=AsyncMock,
@@ -2060,57 +1875,30 @@ async def test_delta_no_merging_on_first_sync_after_reset(team, postgres_config,
)
await _replay_v3_consumer(team_id=inputs.team_id, schema_id=inputs.external_data_schema_id)
- if pipeline_mode == "non_dlt":
- mock_post_run_operations.assert_called_once()
-
- mock_merge.assert_not_called()
- assert mock_write.call_count == 2
-
- _, first_call_kwargs = mock_write.call_args_list[0]
- _, second_call_kwargs = mock_write.call_args_list[1]
+ mock_v3_post_load.assert_called_once()
+ mock_merge.assert_not_called()
+ assert mock_write.call_count == 2
- assert first_call_kwargs == {
- "mode": "overwrite",
- "schema_mode": "overwrite",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
+ _, first_call_kwargs = mock_write.call_args_list[0]
+ _, second_call_kwargs = mock_write.call_args_list[1]
- assert second_call_kwargs == {
- "mode": "append",
- "schema_mode": "merge",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
- else:
- mock_v3_post_load.assert_called_once()
- mock_merge.assert_not_called()
- assert mock_write.call_count == 2
-
- _, first_call_kwargs = mock_write.call_args_list[0]
- _, second_call_kwargs = mock_write.call_args_list[1]
-
- assert first_call_kwargs == {
- "mode": "overwrite",
- "schema_mode": "overwrite",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
+ assert first_call_kwargs == {
+ "mode": "overwrite",
+ "schema_mode": "overwrite",
+ "table_or_uri": mock.ANY,
+ "data": mock.ANY,
+ "partition_by": mock.ANY,
+ "commit_properties": mock.ANY,
+ }
- assert second_call_kwargs == {
- "mode": "append",
- "schema_mode": "merge",
- "table_or_uri": mock.ANY,
- "data": mock.ANY,
- "partition_by": mock.ANY,
- "commit_properties": mock.ANY,
- }
+ assert second_call_kwargs == {
+ "mode": "append",
+ "schema_mode": "merge",
+ "table_or_uri": mock.ANY,
+ "data": mock.ANY,
+ "partition_by": mock.ANY,
+ "commit_properties": mock.ANY,
+ }
@pytest.mark.django_db(transaction=True)
@@ -2252,7 +2040,7 @@ async def test_partition_folders_with_uuid_id_and_created_at(team, postgres_conf
async def test_in_place_repartition_to_finer_datetime_format(team, postgres_config, postgres_connection, minio_client):
# A datetime-partitioned table that has outgrown its scheme is repartitioned in place to a finer
# (daily) layout from the data already in S3 — no source re-pull — and the next incremental merge
- # then runs against the new layout. Runs the whole pipeline (V2 + V3 via the pipeline_mode fixture).
+ # then runs against the new layout. Runs the whole pipeline.
await postgres_connection.execute(
"CREATE TABLE IF NOT EXISTS {schema}.test_repartition (id uuid PRIMARY KEY, created_at timestamp)".format(
schema=postgres_config["schema"]
@@ -2798,18 +2586,11 @@ async def test_partition_folders_with_existing_table(team, postgres_config, post
)
await postgres_connection.commit()
- async def mock_setup_partitioning(pa_table, existing_delta_table, schema, resource, logger):
- return pa_table
-
def mock_apply_partitioning(export_signal, pa_table, existing_delta_table, schema):
return pa_table
# Emulate an existing table with no partitions
with (
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline.setup_partitioning",
- mock_setup_partitioning,
- ),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor._apply_partitioning",
mock_apply_partitioning,
@@ -2898,18 +2679,11 @@ async def test_partition_folders_with_existing_table_and_pipeline_reset(
)
await postgres_connection.commit()
- async def mock_setup_partitioning(pa_table, existing_delta_table, schema, resource, logger):
- return pa_table
-
def mock_apply_partitioning(export_signal, pa_table, existing_delta_table, schema):
return pa_table
# Emulate an existing table with no partitions
with (
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline.setup_partitioning",
- mock_setup_partitioning,
- ),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor._apply_partitioning",
mock_apply_partitioning,
@@ -2989,7 +2763,7 @@ async def test_partition_folders_with_existing_table_and_pipeline_reset(
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_partition_folders_delta_merge_called_with_partition_predicate(
- team, postgres_config, postgres_connection, pipeline_mode
+ team, postgres_config, postgres_connection
):
await postgres_connection.execute(
"CREATE TABLE IF NOT EXISTS {schema}.test_partition_folders (id integer, created_at timestamp)".format(
@@ -3044,7 +2818,6 @@ async def test_partition_folders_delta_merge_called_with_partition_predicate(
),
mock.patch.object(DeltaTable, "merge") as mock_merge,
mock.patch.object(deltalake, "write_deltalake") as mock_write,
- mock.patch.object(PipelineNonDLT, "_post_run_operations") as mock_post_run_operations,
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.run_post_load_operations",
new_callable=AsyncMock,
@@ -3067,10 +2840,7 @@ async def test_partition_folders_delta_merge_called_with_partition_predicate(
)
await _replay_v3_consumer(team_id=inputs.team_id, schema_id=inputs.external_data_schema_id)
- if pipeline_mode == "non_dlt":
- mock_post_run_operations.assert_called_once()
- else:
- mock_v3_post_load.assert_called_once()
+ mock_v3_post_load.assert_called_once()
mock_write.assert_not_called()
assert mock_merge.call_count == 1
@@ -3102,9 +2872,7 @@ async def test_row_tracking_incrementing(team, postgres_config, postgres_connect
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract.decrement_rows"
) as mock_decrement_rows,
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.external_data_job.finish_row_tracking"
- ) as mock_finish_row_tracking_workflow,
+ mock.patch("products.warehouse_sources.backend.temporal.data_imports.external_data_job.finish_row_tracking"),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.finish_row_tracking"
) as mock_finish_row_tracking_consumer,
@@ -3129,10 +2897,7 @@ async def test_row_tracking_incrementing(team, postgres_config, postgres_connect
schema_id = inputs.external_data_schema_id
mock_decrement_rows.assert_called_once_with(team.id, schema_id, 1)
- if _current_pipeline_mode == "v3":
- mock_finish_row_tracking_consumer.assert_called_once()
- else:
- mock_finish_row_tracking_workflow.assert_called_once()
+ mock_finish_row_tracking_consumer.assert_called_once()
assert schema_id is not None
with override_settings(
@@ -3373,11 +3138,8 @@ async def test_worker_shutdown_triggers_schedule_buffer_one(team, zendesk_brands
)()
assert run is not None
- if _current_pipeline_mode == "v3":
- assert run.status == ExternalDataJobStatus.FAILED
- assert run.latest_error == WORKER_RESTART_ERROR_MESSAGE
- else:
- assert run.status == ExternalDataJobStatus.COMPLETED
+ assert run.status == ExternalDataJobStatus.FAILED
+ assert run.latest_error == WORKER_RESTART_ERROR_MESSAGE
@pytest.mark.django_db(transaction=True)
@@ -3535,11 +3297,11 @@ async def test_billing_limits_too_many_rows_previously(team, postgres_config, po
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_pipeline_mb_chunk_size(team, zendesk_brands, pipeline_mode):
- if pipeline_mode == "v3":
- process_mock = mock.patch.object(PipelineV3, "_process_batch", new_callable=AsyncMock)
- else:
- process_mock = mock.patch.object(PipelineNonDLT, "_process_pa_table")
+async def test_pipeline_mb_chunk_size(
+ team,
+ zendesk_brands,
+):
+ process_mock = mock.patch.object(PipelineV3, "_process_batch", new_callable=AsyncMock)
with (
mock.patch(
@@ -3804,9 +3566,6 @@ async def test_v3_delta_commit_metadata_and_idempotency_fallback(team, stripe_cu
would otherwise re-write the same batch and produce duplicate rows. The delta-history
fallback closes that gap.
"""
- if _current_pipeline_mode != "v3":
- pytest.skip("only applies to pipeline_v3")
-
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.idempotency import (
is_batch_already_processed,
)
@@ -3906,11 +3665,12 @@ async def test_v3_delta_commit_metadata_and_idempotency_fallback(team, stripe_cu
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
[email protected]("pipeline_mode", ["non_dlt"], indirect=True)
-async def test_non_retryable_error_short_circuiting(team, stripe_customer, mock_stripe_client, pipeline_mode):
- # The retry/short-circuit behaviour lives in the workflow + activity layer, upstream of the
- # v3/non_dlt split, so running a single pipeline mode is enough — running both just doubles the
- # cost. Each attempt re-executes the whole import activity, so we also shrink the retry budgets
+async def test_non_retryable_error_short_circuiting(
+ team,
+ stripe_customer,
+ mock_stripe_client,
+):
+ # The retry/short-circuit behaviour lives in the workflow + activity layer. Each attempt re-executes the whole import activity, so we also shrink the retry budgets
# to keep the test fast: cap resumable retries at 3 and make the non-retryable path give up after
# 2 attempts. The contrast (3 retryable attempts vs 2 non-retryable attempts) is what proves the
# short-circuit; the prod caps (20 / 3) are just larger values of the same mechanism.
@@ -4034,7 +3794,12 @@ async def test_cdp_producer_push_to_s3(team, stripe_customer, mock_stripe_client
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_cdp_producer_push_to_kafka(team, stripe_customer, mock_stripe_client, minio_client, pipeline_mode):
+async def test_cdp_producer_push_to_kafka(
+ team,
+ stripe_customer,
+ mock_stripe_client,
+ minio_client,
+):
await sync_to_async(HogFunction.objects.create)(
team=team,
enabled=True,
@@ -4058,7 +3823,7 @@ async def test_cdp_producer_push_to_kafka(team, stripe_customer, mock_stripe_cli
_fake_scope,
),
mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline.time.time_ns",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.time.time_ns",
return_value=1768828644858352000,
),
):
@@ -4103,10 +3868,6 @@ async def test_cdp_producer_push_to_kafka(team, stripe_customer, mock_stripe_cli
"_ph_debug": '{"load_id": 1768828644858352000}',
}
- # non_dlt adds _ph_partition_key during extract; v3 applies partitioning in the consumer
- if pipeline_mode == "non_dlt":
- expected_properties["_ph_partition_key"] = "2023-w14"
-
# The producer derives a deterministic event id per row per job. Its value depends on the
# dynamic job id, so assert it is a valid UUID and compare the rest of the payload.
data = call_kwargs["data"]
@@ -4494,11 +4255,13 @@ async def _mysql_setup(mysql_connection, statements: list[tuple[str, tuple | Non
await sync_to_async(_run)()
-# test_mysql_source_full_refresh covers the non-DLT path against real MySQL.
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
[email protected]("pipeline_mode", ["v3"], indirect=True)
-async def test_mysql_full_refresh(team, mysql_config, mysql_connection, pipeline_mode):
+async def test_mysql_full_refresh(
+ team,
+ mysql_config,
+ mysql_connection,
+):
"""Full-refresh sync of a simple table with a mix of common MySQL types."""
await _mysql_setup(
mysql_connection,
@@ -4539,11 +4302,13 @@ async def test_mysql_full_refresh(team, mysql_config, mysql_connection, pipeline
assert row[2] == 30
-# test_mysql_source_incremental covers the non-DLT path against real MySQL.
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
[email protected]("pipeline_mode", ["v3"], indirect=True)
-async def test_mysql_incremental_integer_cursor(team, mysql_config, mysql_connection, pipeline_mode):
+async def test_mysql_incremental_integer_cursor(
+ team,
+ mysql_config,
+ mysql_connection,
+):
"""Incremental sync with an INT cursor field — second run should pick up only new rows."""
await _mysql_setup(
mysql_connection,
@@ -5083,9 +4848,6 @@ async def _destination_rows(postgres_config: dict, table: str) -> list[tuple]:
async def test_a_source_syncs_to_a_postgres_destination(
team, stripe_charge, mock_stripe_client, postgres_config, setup_postgres_test_db
):
- if _current_pipeline_mode != "v3":
- pytest.skip("destinations only apply to pipeline_v3")
-
destination = await _postgres_destination(team, postgres_config)
warehouse = await sync_to_async(get_or_create_warehouse_destination)(team.pk)
@@ -5112,9 +4874,6 @@ async def test_a_source_syncs_to_a_postgres_destination(
async def test_a_run_with_a_destination_bills_for_both(
team, stripe_charge, mock_stripe_client, postgres_config, setup_postgres_test_db
):
- if _current_pipeline_mode != "v3":
- pytest.skip("destinations only apply to pipeline_v3")
-
destination = await _postgres_destination(team, postgres_config)
warehouse = await sync_to_async(get_or_create_warehouse_destination)(team.pk)
@@ -5140,9 +4899,6 @@ async def test_a_run_with_a_destination_bills_for_both(
async def test_a_second_sync_merges_into_the_destination_rather_than_duplicating(
team, stripe_charge, mock_stripe_client, postgres_config, setup_postgres_test_db
):
- if _current_pipeline_mode != "v3":
- pytest.skip("destinations only apply to pipeline_v3")
-
destination = await _postgres_destination(team, postgres_config)
warehouse = await sync_to_async(get_or_create_warehouse_destination)(team.pk)
run_kwargs: dict[str, Any] = {
@@ -5180,9 +4936,6 @@ async def test_a_source_can_sync_to_a_destination_and_not_to_posthog(
copy. It is also the trap, since selecting a destination and expecting to keep the
warehouse would silently stop the PostHog side.
"""
- if _current_pipeline_mode != "v3":
- pytest.skip("destinations only apply to pipeline_v3")
-
destination = await _postgres_destination(team, postgres_config)
await _run(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py
index 35a441002392..82572aa16f9e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_external_data_job.py
@@ -1,5 +1,4 @@
import uuid
-import functools
from concurrent.futures import ThreadPoolExecutor
from typing import Optional
@@ -9,9 +8,6 @@ from unittest import mock
from django.conf import settings
from django.test import override_settings
-import boto3
-import psycopg
-import pytest_asyncio
from asgiref.sync import sync_to_async
from temporalio.common import RetryPolicy
from temporalio.testing import WorkflowEnvironment
@@ -34,7 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_job
create_source_templates,
update_external_data_job_model,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLT
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
from products.warehouse_sources.backend.temporal.data_imports.settings import import_data_activity_sync
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (
BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,
@@ -45,7 +41,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.set
ENDPOINTS as STRIPE_ENDPOINTS,
)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (
- check_pipeline_version_activity,
+ acquire_v3_pipeline_lock_activity,
+ release_v3_pipeline_lock_activity,
)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (
calculate_table_size_activity,
@@ -57,88 +54,12 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
CreateExternalDataJobModelActivityInputs,
create_external_data_job_model_activity,
)
-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.import_data_sync import (
- ImportDataActivityInputs,
-)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.sync_new_schemas import (
SyncNewSchemasActivityInputs,
sync_new_schemas_activity,
)
BUCKET_NAME = "test-pipeline"
-SESSION = boto3.Session()
-create_test_client = functools.partial(SESSION.client, endpoint_url=settings.OBJECT_STORAGE_ENDPOINT)
-
-
-def delete_all_from_s3(minio_client, bucket_name: str, key_prefix: str):
- """Delete all objects in bucket_name under key_prefix."""
- response = minio_client.list_objects_v2(Bucket=bucket_name, Prefix=key_prefix)
-
- if "Contents" in response:
- for obj in response["Contents"]:
- if "Key" in obj:
- minio_client.delete_object(Bucket=bucket_name, Key=obj["Key"])
-
-
-def bucket_name(request) -> str:
- """Name for a test S3 bucket."""
- return BUCKET_NAME
-
-
-def minio_client(bucket_name):
- """Manage an S3 client to interact with a MinIO bucket.
-
- Yields the client after creating a bucket. Upon resuming, we delete
- the contents and the bucket itself.
- """
- minio_client = create_test_client(
- "s3",
- aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
- aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
- )
-
- try:
- minio_client.head_bucket(Bucket=bucket_name)
- except:
- minio_client.create_bucket(Bucket=bucket_name)
-
- yield minio_client
-
- delete_all_from_s3(minio_client, bucket_name, key_prefix="")
-
- try:
- minio_client.delete_bucket(Bucket=bucket_name)
- except:
- pass
-
-
-def postgres_config():
- return {
- "user": settings.PG_USER,
- "password": settings.PG_PASSWORD,
- "database": "external_data_database",
- "schema": "external_data_schema",
- "host": settings.PG_HOST,
- "port": int(settings.PG_PORT),
- }
-
-
-@pytest_asyncio.fixture
-async def postgres_connection(postgres_config, setup_postgres_test_db):
- connection = await psycopg.AsyncConnection.connect(
- user=postgres_config["user"],
- password=postgres_config["password"],
- dbname=postgres_config["database"],
- host=postgres_config["host"],
- port=postgres_config["port"],
- )
-
- yield connection
-
- await connection.close()
def _create_schema(schema_name: str, source: ExternalDataSource, team: Team, table_id: Optional[str] = None):
@@ -713,240 +634,6 @@ def test_invalid_ssh_tunnel_auth_is_non_retryable_for_any_source(error_msg):
assert is_non_retryable, f"Invalid SSH tunnel auth error should be non-retryable: {error_msg}"
-def mock_stripe_client():
- with mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe.StripeClient"
- ) as MockStripeClient:
- mock_balance_transaction_list = mock.MagicMock()
- mock_charges_list = mock.MagicMock()
- mock_customers_list = mock.MagicMock()
- mock_invoice_list = mock.MagicMock()
- mock_price_list = mock.MagicMock()
- mock_product_list = mock.MagicMock()
- mock_subscription_list = mock.MagicMock()
-
- mock_charges_list.auto_paging_iter.return_value = [
- {
- "id": "chg_123",
- "customer": "cus_1",
- "created": 123,
- }
- ]
- mock_customers_list.auto_paging_iter.return_value = [
- {
- "id": "cus_123",
- "name": "John Doe",
- "created": 123,
- }
- ]
-
- instance = MockStripeClient.return_value
- instance.balance_transactions.list.return_value = mock_balance_transaction_list
- instance.charges.list.return_value = mock_charges_list
- instance.customers.list.return_value = mock_customers_list
- instance.invoices.list.return_value = mock_invoice_list
- instance.prices.list.return_value = mock_price_list
- instance.products.list.return_value = mock_product_list
- instance.subscriptions.list.return_value = mock_subscription_list
-
- yield instance
-
-
[email protected]_db(transaction=True)
-async def test_run_stripe_job(activity_environment, team, minio_client, mock_stripe_client, **kwargs):
- def setup_job_1():
- new_source = ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Stripe",
- job_inputs={
- "auth_method": {"selection": "api_key", "stripe_secret_key": "test-key"},
- "stripe_account_id": "acct_id",
- },
- )
-
- customer_schema = _create_schema(STRIPE_CUSTOMER_RESOURCE_NAME, new_source, team)
-
- new_job: ExternalDataJob = ExternalDataJob.objects.create(
- team_id=team.id,
- pipeline_id=new_source.pk,
- status=ExternalDataJob.Status.RUNNING,
- rows_synced=0,
- schema=customer_schema,
- pipeline_version=ExternalDataJob.PipelineVersion.V1,
- )
-
- new_job = ExternalDataJob.objects.get(id=new_job.id)
-
- inputs = ImportDataActivityInputs(
- team_id=team.id,
- run_id=str(new_job.pk),
- source_id=new_source.pk,
- schema_id=customer_schema.id,
- )
-
- return new_job, inputs
-
- def setup_job_2():
- new_source = ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Stripe",
- job_inputs={
- "auth_method": {"selection": "api_key", "stripe_secret_key": "test-key"},
- "stripe_account_id": "acct_id",
- },
- )
-
- charge_schema = _create_schema(STRIPE_CHARGE_RESOURCE_NAME, new_source, team)
-
- new_job: ExternalDataJob = ExternalDataJob.objects.create(
- team_id=team.id,
- pipeline_id=new_source.pk,
- status=ExternalDataJob.Status.RUNNING,
- rows_synced=0,
- schema=charge_schema,
- pipeline_version=ExternalDataJob.PipelineVersion.V1,
- )
-
- new_job = ExternalDataJob.objects.get(id=new_job.id)
-
- inputs = ImportDataActivityInputs(
- team_id=team.id,
- run_id=str(new_job.pk),
- source_id=new_source.pk,
- schema_id=charge_schema.id,
- )
-
- return new_job, inputs
-
- job_1, job_1_inputs = await sync_to_async(setup_job_1)()
- job_2, job_2_inputs = await sync_to_async(setup_job_2)()
-
- with (
- override_settings(
- BUCKET_URL=f"s3://{BUCKET_NAME}",
- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
- BUCKET_NAME=BUCKET_NAME,
- ),
- mock.patch(
- "products.warehouse_sources.backend.models.table.DataWarehouseTable.get_columns",
- return_value={
- "id": {"clickhouse": "string", "hogql": "StringDatabaseField"},
- "name": {"clickhouse": "string", "hogql": "StringDatabaseField"},
- },
- ),
- ):
- await activity_environment.run(import_data_activity_sync, job_1_inputs)
-
- folder_path = await sync_to_async(job_1.folder_path)()
- job_1_customer_objects = minio_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=f"{folder_path}/customer/")
-
- assert len(job_1_customer_objects["Contents"]) == 3
-
- with (
- override_settings(
- BUCKET_URL=f"s3://{BUCKET_NAME}",
- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
- BUCKET_NAME=BUCKET_NAME,
- ),
- mock.patch(
- "products.warehouse_sources.backend.models.table.DataWarehouseTable.get_columns",
- return_value={
- "id": {"clickhouse": "string", "hogql": "StringDatabaseField"},
- "customer": {"clickhouse": "string", "hogql": "StringDatabaseField"},
- },
- ),
- ):
- await activity_environment.run(import_data_activity_sync, job_2_inputs)
-
- job_2_folder_path = await sync_to_async(job_2.folder_path)()
- job_2_charge_objects = minio_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=f"{job_2_folder_path}/charge/")
- assert len(job_2_charge_objects["Contents"]) == 3
-
-
[email protected]_db(transaction=True)
-async def test_run_stripe_job_row_count_update(activity_environment, team, minio_client, mock_stripe_client, **kwargs):
- def setup_job_1():
- new_source = ExternalDataSource.objects.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- team=team,
- status="running",
- source_type="Stripe",
- job_inputs={
- "auth_method": {"selection": "api_key", "stripe_secret_key": "test-key"},
- "stripe_account_id": "acct_id",
- },
- )
-
- customer_schema = _create_schema(STRIPE_CUSTOMER_RESOURCE_NAME, new_source, team)
-
- new_job: ExternalDataJob = ExternalDataJob.objects.create(
- team_id=team.id,
- pipeline_id=new_source.pk,
- status=ExternalDataJob.Status.RUNNING,
- rows_synced=0,
- schema=customer_schema,
- pipeline_version=ExternalDataJob.PipelineVersion.V1,
- )
-
- new_job = (
- ExternalDataJob.objects.filter(id=new_job.id).prefetch_related("pipeline").prefetch_related("schema").get()
- )
-
- inputs = ImportDataActivityInputs(
- team_id=team.id,
- run_id=str(new_job.pk),
- source_id=new_source.pk,
- schema_id=customer_schema.id,
- )
-
- return new_job, inputs
-
- job_1, job_1_inputs = await sync_to_async(setup_job_1)()
-
- with (
- override_settings(
- BUCKET_URL=f"s3://{BUCKET_NAME}",
- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
- BUCKET_NAME=BUCKET_NAME,
- ),
- mock.patch(
- "products.warehouse_sources.backend.models.table.DataWarehouseTable.get_columns",
- return_value={
- "id": {"clickhouse": "string", "hogql": "StringDatabaseField"},
- "name": {"clickhouse": "string", "hogql": "StringDatabaseField"},
- },
- ),
- ):
- await activity_environment.run(import_data_activity_sync, job_1_inputs)
-
- folder_path = await sync_to_async(job_1.folder_path)()
- job_1_customer_objects = minio_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=f"{folder_path}/customer/")
-
- assert len(job_1_customer_objects["Contents"]) == 3
-
- await sync_to_async(job_1.refresh_from_db)()
- assert job_1.rows_synced == 1
-
-
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_external_data_job_workflow_with_schema(team, **kwargs):
@@ -987,7 +674,7 @@ async def test_external_data_job_workflow_with_schema(team, **kwargs):
"products.warehouse_sources.backend.models.table.DataWarehouseTable.get_columns",
return_value={"id": "string"},
),
- mock.patch.object(PipelineNonDLT, "run", mock_func),
+ mock.patch.object(PipelineV3, "run", mock_func),
):
with (
override_settings(
@@ -1005,7 +692,8 @@ async def test_external_data_job_workflow_with_schema(team, **kwargs):
task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,
workflows=[ExternalDataJobWorkflow],
activities=[
- check_pipeline_version_activity,
+ acquire_v3_pipeline_lock_activity,
+ release_v3_pipeline_lock_activity,
create_external_data_job_model_activity,
update_external_data_job_model,
import_data_activity_sync,
@@ -1030,73 +718,3 @@ async def test_external_data_job_workflow_with_schema(team, **kwargs):
assert run is not None
assert run.status == ExternalDataJob.Status.COMPLETED
-
-
[email protected]_db(transaction=True)
-async def test_run_postgres_job(
- activity_environment, team, minio_client, postgres_connection, postgres_config, **kwargs
-):
- await postgres_connection.execute(
- "CREATE TABLE IF NOT EXISTS {schema}.posthog_test (id integer)".format(schema=postgres_config["schema"])
- )
- await postgres_connection.execute(
- "INSERT INTO {schema}.posthog_test (id) VALUES (1)".format(schema=postgres_config["schema"])
- )
- await postgres_connection.commit()
-
- async def setup_job_1():
- new_source = await sync_to_async(ExternalDataSource.objects.create)(
- source_id=uuid.uuid4(),
- connection_id=uuid.uuid4(),
- destination_id=uuid.uuid4(),
- team=team,
- status="running",
- source_type="Postgres",
- job_inputs={
- "host": postgres_config["host"],
- "port": postgres_config["port"],
- "database": postgres_config["database"],
- "user": postgres_config["user"],
- "password": postgres_config["password"],
- "schema": postgres_config["schema"],
- "ssh_tunnel_enabled": False,
- },
- )
-
- posthog_test_schema = await sync_to_async(_create_schema)("posthog_test", new_source, team)
-
- new_job: ExternalDataJob = await sync_to_async(ExternalDataJob.objects.create)(
- team_id=team.id,
- pipeline_id=new_source.pk,
- status=ExternalDataJob.Status.RUNNING,
- rows_synced=0,
- schema=posthog_test_schema,
- pipeline_version=ExternalDataJob.PipelineVersion.V1,
- )
-
- new_job = await sync_to_async(
- ExternalDataJob.objects.filter(id=new_job.id).prefetch_related("pipeline").prefetch_related("schema").get
- )()
-
- inputs = ImportDataActivityInputs(
- team_id=team.id, run_id=str(new_job.pk), source_id=new_source.pk, schema_id=posthog_test_schema.id
- )
-
- return new_job, inputs
-
- job_1, job_1_inputs = await setup_job_1()
-
- with override_settings(
- BUCKET_URL=f"s3://{BUCKET_NAME}",
- BUCKET_PATH=BUCKET_NAME,
- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",
- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",
- ):
- await activity_environment.run(import_data_activity_sync, job_1_inputs)
-
- folder_path = await sync_to_async(job_1.folder_path)()
- job_1_team_objects = minio_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=f"{folder_path}/posthog_test/")
- assert len(job_1_team_objects["Contents"]) == 3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
index 3edb82dec90e..2ff051c4a1b1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
@@ -69,7 +69,7 @@ def _setup(
status=ExternalDataJob.Status.RUNNING,
rows_synced=0,
workflow_id="some_workflow_id",
- pipeline_version=ExternalDataJob.PipelineVersion.V1,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
)
return ImportDataActivityInputs(team_id=team.pk, schema_id=schema.pk, source_id=source.pk, run_id=str(job.pk))
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 892586bfbdfa..f9849a0a395b 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
@@ -1,11 +1,11 @@
-"""The V2/V3 post-import fork in `external-data-job`.
+"""The post-import fork in `external-data-job`.
-The load-dependent post-import steps run only in `data-import-post-import`: V3 runs
+The load-dependent post-import steps run only in `data-import-post-import`: runs
with batches rely on the load consumer to start it after the final batch loads, while
-V2 (and zero-batch V3) start it from `external-data-job` after the COMPLETED status
-write. If the workflow-side trigger is dropped, V2 syncs silently lose every step; if
+zero-batch runs start it from `external-data-job` after the COMPLETED status write.
+If the workflow-side trigger is dropped, zero-batch syncs silently lose every step; if
it fires before the status write, the resolve activity skips them all; if it
-over-applies, V3-with-batches double-triggers or externally managed schemas gain a
+over-applies, runs with batches double-trigger or externally managed schemas gain a
fan-out they never had.
"""
@@ -61,7 +61,6 @@ _SCHEMA_ID = uuid.UUID("01960000-0000-0000-0000-000000000001")
def _stub_activities(
executed: list[str],
*,
- is_v3: bool,
consumer_manages_job_status: bool,
skip_post_import_activities: bool = False,
fast_return_eligible: bool = False,
@@ -75,7 +74,7 @@ def _stub_activities(
@activity.defn(name="check_pipeline_version_activity")
async def check_pipeline_version(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:
executed.append("check_pipeline_version_activity")
- return CheckPipelineVersionActivityOutputs(is_v3=is_v3)
+ return CheckPipelineVersionActivityOutputs(is_v3=True)
@activity.defn(name="acquire_v3_pipeline_lock_activity")
async def acquire_lock(inputs: AcquireV3LockActivityInputs) -> AcquireV3LockActivityOutputs:
@@ -164,7 +163,6 @@ def _stub_activities(
async def _run_workflow(
*,
- is_v3: bool,
consumer_manages_job_status: bool,
skip_post_import_activities: bool = False,
fast_return_eligible: bool = False,
@@ -199,7 +197,6 @@ async def _run_workflow(
workflows=[ExternalDataJobWorkflow],
activities=_stub_activities(
executed,
- is_v3=is_v3,
consumer_manages_job_status=consumer_manages_job_status,
skip_post_import_activities=skip_post_import_activities,
fast_return_eligible=fast_return_eligible,
@@ -240,32 +237,32 @@ LOAD_DEPENDENT_CHILD_PREFIXES = (
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "is_v3,consumer_manages_job_status,skip_post_import_activities,expect_post_import_child",
+ "consumer_manages_job_status,skip_post_import_activities,expect_post_import_child",
[
- # V2: the workflow starts data-import-post-import after the COMPLETED write.
- pytest.param(False, False, False, True, id="v2_starts_post_import_workflow"),
- # V3 with zero batches: the consumer never sees a final batch, so the workflow keeps ownership.
- pytest.param(True, False, False, True, id="v3_zero_batches_starts_post_import_workflow"),
- # V3 with batches: the load consumer starts data-import-post-import; starting it here
+ # Zero batches: the consumer never sees a final batch, so the workflow keeps ownership.
+ pytest.param(False, False, True, id="zero_batches_starts_post_import_workflow"),
+ # With batches: the load consumer starts data-import-post-import; starting it here
# too would race the consumer's load.
- pytest.param(True, True, False, False, id="v3_with_batches_leaves_trigger_to_consumer"),
+ pytest.param(True, False, False, id="with_batches_leaves_trigger_to_consumer"),
# Externally managed schemas never ran the post-import steps; the finally-block
# trigger must not give them a fan-out.
- pytest.param(False, False, True, False, id="externally_managed_schema_gets_no_post_import"),
+ pytest.param(False, True, False, id="externally_managed_schema_gets_no_post_import"),
],
)
async def test_post_import_fork(
- is_v3: bool,
consumer_manages_job_status: bool,
skip_post_import_activities: bool,
expect_post_import_child: bool,
):
executed, child_ids = await _run_workflow(
- is_v3=is_v3,
consumer_manages_job_status=consumer_manages_job_status,
skip_post_import_activities=skip_post_import_activities,
)
+ # New executions skip the version check and always take the V3 lock first.
+ assert "check_pipeline_version_activity" not in executed
+ assert executed[0] == "acquire_v3_pipeline_lock_activity"
+
# The load-dependent steps never run inline in new executions — data-import-post-import
# is their only home (the inline path survives solely for pre-patch replay).
started = {prefix for prefix in LOAD_DEPENDENT_CHILD_PREFIXES if any(c.startswith(prefix) for c in child_ids)}
@@ -301,7 +298,6 @@ async def test_fast_return_skips_post_import_only_when_the_source_is_unchanged(
fast_return_eligible: bool, source_has_new_data: bool, expect_fast_return: bool
):
executed, child_ids = await _run_workflow(
- is_v3=False,
consumer_manages_job_status=False,
fast_return_eligible=fast_return_eligible,
source_has_new_data=source_has_new_data,
@@ -319,9 +315,7 @@ async def test_fast_return_skips_post_import_only_when_the_source_is_unchanged(
@pytest.mark.asyncio
@pytest.mark.parametrize("scheduled_full_refresh", [True, False])
async def test_the_import_learns_a_run_is_a_scheduled_full_refresh(scheduled_full_refresh: bool):
- executed, _ = await _run_workflow(
- is_v3=False, consumer_manages_job_status=False, scheduled_full_refresh=scheduled_full_refresh
- )
+ executed, _ = await _run_workflow(consumer_manages_job_status=False, scheduled_full_refresh=scheduled_full_refresh)
assert ("import_data_activity_sync:scheduled_full_refresh" in executed) is scheduled_full_refresh
assert ("maybe_repartition_table_activity" in executed) is not scheduled_full_refresh
@@ -332,9 +326,7 @@ async def test_the_import_learns_a_run_is_a_scheduled_full_refresh(scheduled_ful
async def test_repartition_activity_is_scheduled_only_when_job_creation_finds_work(repartition_needed: bool):
# The activity round trip is most of what a healthy sync paid for repartitioning; the
# job-creation activity already knows whether anything is queued or due for measurement.
- executed, _ = await _run_workflow(
- is_v3=False, consumer_manages_job_status=False, repartition_needed=repartition_needed
- )
+ executed, _ = await _run_workflow(consumer_manages_job_status=False, repartition_needed=repartition_needed)
assert ("maybe_repartition_table_activity" in executed) is repartition_needed
assert "import_data_activity_sync" in executed
@@ -353,7 +345,6 @@ async def test_billing_limit_answered_by_job_creation_skips_the_check_activity(
billing_limit_checked: bool, hit_billing_limit: bool, expect_check_activity: bool, expect_import: bool
) -> None:
executed, _ = await _run_workflow(
- is_v3=False,
consumer_manages_job_status=False,
billing_limit_checked=billing_limit_checked,
hit_billing_limit=hit_billing_limit,
@@ -371,7 +362,7 @@ async def test_billing_limit_answered_by_job_creation_skips_the_check_activity(
@pytest.mark.parametrize("source_templates_needed", [True, False])
async def test_source_templates_activity_runs_only_when_job_creation_finds_work(source_templates_needed: bool) -> None:
executed, _ = await _run_workflow(
- is_v3=False, consumer_manages_job_status=False, source_templates_needed=source_templates_needed
+ consumer_manages_job_status=False, source_templates_needed=source_templates_needed
)
assert ("create_source_templates" in executed) is source_templates_needed
@@ -380,17 +371,16 @@ async def test_source_templates_activity_runs_only_when_job_creation_finds_work(
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "is_v3,consumer_manages_job_status,expect_finalizer_releases",
+ "consumer_manages_job_status,expect_finalizer_releases",
[
- pytest.param(True, False, True, id="v3_zero_batches_finalizer_releases"),
- pytest.param(True, True, False, id="v3_with_batches_leaves_lock_to_the_loader"),
- pytest.param(False, False, False, id="v2_has_no_lock"),
+ pytest.param(False, True, id="zero_batches_finalizer_releases"),
+ pytest.param(True, False, id="with_batches_leaves_lock_to_the_loader"),
],
)
async def test_v3_lock_release_rides_the_finalizer(
- is_v3: bool, consumer_manages_job_status: bool, expect_finalizer_releases: bool
+ consumer_manages_job_status: bool, expect_finalizer_releases: bool
) -> None:
- executed, _ = await _run_workflow(is_v3=is_v3, consumer_manages_job_status=consumer_manages_job_status)
+ executed, _ = await _run_workflow(consumer_manages_job_status=consumer_manages_job_status)
assert "release_v3_pipeline_lock_activity" not in executed
assert ("update_external_data_job_model:release_lock_token=token" in executed) is expect_finalizer_releases
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
index e3c597853105..2543b9cdb33e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
@@ -19,9 +19,6 @@ from posthog.temporal.common.logger import get_logger
from products.data_warehouse.backend.facade.api import update_external_job_status
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
-from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import scheduled_sync_consumes_buffer
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
LOCK_TAKEOVER_LATEST_ERROR,
TERMINAL_JOB_STATUSES,
@@ -33,10 +30,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
release_v3_pipeline_lock,
write_v3_pipeline_lock_meta,
)
-from products.warehouse_sources.backend.temporal.data_imports.util import with_internal_db_retries
-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
- is_pipeline_v3_enabled,
-)
from products.warehouse_sources_queue.backend.sdk import BatchQueue
LOGGER = get_logger(__name__)
@@ -83,30 +76,10 @@ class ReleaseV3LockActivityInputs:
@activity.defn
-@with_internal_db_retries
def check_pipeline_version_activity(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:
- bind_contextvars(team_id=inputs.team_id)
- close_old_connections()
-
- # Buffered CDC consumption requires the v3 loader, whose position resolution proves buffer
- # files consumed, so it overrides the rollout flag: the same V3 the CDC extraction hardcodes
- # for the jobs it creates.
- if inputs.schema_id is not None:
- schema = (
- ExternalDataSchema.objects.filter(id=inputs.schema_id, team_id=inputs.team_id)
- .select_related("source")
- .first()
- )
- if schema is not None and scheduled_sync_consumes_buffer(schema):
- return CheckPipelineVersionActivityOutputs(is_v3=True)
-
- try:
- source = ExternalDataSource.objects.get(id=inputs.source_id)
- except ExternalDataSource.DoesNotExist:
- return CheckPipelineVersionActivityOutputs(is_v3=False)
-
- is_v3 = is_pipeline_v3_enabled(inputs.team_id, source.source_type)
- return CheckPipelineVersionActivityOutputs(is_v3=is_v3)
+ # Only a workflow history recorded before the "data-imports-v3-only-2026-10" patch schedules
+ # this activity. Every run is V3 now, so the answer is fixed.
+ return CheckPipelineVersionActivityOutputs(is_v3=True)
@activity.defn
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index 3234503e9048..dd9dddf9c615 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -8,11 +8,9 @@ from django.db import IntegrityError, close_old_connections
from django.db.models import Max
from django.utils import timezone
-import posthoganalytics
from structlog.contextvars import bind_contextvars
from temporalio import activity
-from posthog.exceptions_capture import capture_exception
from posthog.models.team.team import Team
from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.logger import get_logger
@@ -53,37 +51,6 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
-WAREHOUSE_PIPELINES_V3_FLAG = "warehouse-pipelines-v3"
-
-
-def is_pipeline_v3_enabled(team_id: int, source_type: str) -> bool:
- try:
- team = Team.objects.only("uuid", "organization_id").get(id=team_id)
- except Team.DoesNotExist:
- return False
-
- try:
- return bool(
- posthoganalytics.feature_enabled(
- WAREHOUSE_PIPELINES_V3_FLAG,
- str(team.uuid),
- groups={
- "organization": str(team.organization_id),
- "project": str(team.id),
- },
- group_properties={
- "organization": {"id": str(team.organization_id), "source_type": source_type},
- "project": {"id": str(team.id), "source_type": source_type},
- },
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception as e:
- capture_exception(e)
- return False
-
-
LOGGER = get_logger(__name__)
@@ -110,6 +77,14 @@ class V3PipelineLockLostError(NonReportableError):
"""
+class V2PipelineRemovedError(NonReportableError):
+ """A workflow history recorded before every run moved to V3 asked for a V2 job.
+
+ Only a replay of such a history can send ``is_v3=False``. The V2 pipeline no longer exists,
+ so the run fails before it creates a job and the next scheduled run starts on V3.
+ """
+
+
def _statistics_stale(team_id: int, table: DataWarehouseTable | None) -> bool:
"""Whether column statistics need recomputing: no stats yet, or the freshest column row is older
than the recompute interval. Mirrors compute_table_statistics' own skip check so we don't spawn a
@@ -234,7 +209,8 @@ class CreateExternalDataJobModelActivityInputs:
schema_id: uuid.UUID
source_id: uuid.UUID
billable: bool
- is_v3: bool = False
+ # Always True for new runs. Only a pre-patch workflow history can still send False.
+ is_v3: bool = True
# Admin resyncs and non-billable resumes start the workflow directly and must not become a full refresh.
started_by_schedule: bool = False
@@ -363,21 +339,18 @@ def create_external_data_job_model_activity(
logger.info("Source or schema no longer exists, deleted the sync schedule")
raise SourceOrSchemaDeletedError("Source or schema no longer exists - deleted temporal schedule")
+ if not inputs.is_v3:
+ raise V2PipelineRemovedError("The V2 import pipeline was removed. The next scheduled run uses V3.")
+
try:
schema = ExternalDataSchema.objects.get(team_id=inputs.team_id, id=inputs.schema_id)
source: ExternalDataSource = schema.source
- pipeline_version = ExternalDataJob.PipelineVersion.V2
- if inputs.is_v3:
- pipeline_version = ExternalDataJob.PipelineVersion.V3
- _verify_v3_lock_still_held(inputs.team_id, inputs.schema_id)
+ _verify_v3_lock_still_held(inputs.team_id, inputs.schema_id)
- # Only v3 runs deliver to destinations; v2 has no per-batch queue to carry the ids.
destination_ids: list[str] = []
- if pipeline_version == ExternalDataJob.PipelineVersion.V3 and is_multi_destination_enabled(
- inputs.team_id, source.source_type
- ):
+ if is_multi_destination_enabled(inputs.team_id, source.source_type):
destination_ids = destination_ids_for_run(schema)
# A refresh run skips the repartition activity, the only thing that ends a repartition hold on
# the import. A refresh while the import is held never wipes the table or restarts the clock,
@@ -398,7 +371,7 @@ def create_external_data_job_model_activity(
team_id=inputs.team_id,
source_id=inputs.source_id,
schema_id=inputs.schema_id,
- pipeline_version=pipeline_version,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
billable=inputs.billable,
schema_snapshot=schema_snapshot,
destination_ids=destination_ids,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index a806f5b1797b..f77116a27ea0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -63,7 +63,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import PipelineInputs
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLT
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import setup_row_tracking
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
@@ -97,7 +96,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
validate_and_coerce_row_filters,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.util import PostHogInternalDatabaseError
+from products.warehouse_sources.backend.temporal.data_imports.util import (
+ NonRetryableException,
+ PostHogInternalDatabaseError,
+)
from products.warehouse_sources.backend.temporal.data_imports.workload_report import aworkload_reporting
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -386,20 +388,26 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
model = await _get_external_data_job(inputs.run_id)
- if model.pipeline_version == ExternalDataJob.PipelineVersion.V3:
- attempt = current_activity_attempt()
- if attempt > 1 and model.status in TERMINAL_JOB_STATUSES:
- await logger.ainfo(
- "Skipping retry - job already terminal",
- status=model.status,
- attempt=attempt,
- )
- # The consumer already finalized this run (that's how it became terminal), so the
- # workflow must not overwrite the status or release the lock — see PipelineResult.
- return PipelineResult(
- should_trigger_cdp_producer=False,
- consumer_manages_job_status=True,
- )
+ if model.pipeline_version != ExternalDataJob.PipelineVersion.V3:
+ # Only a job created before every run moved to V3 can get here, and the V2 pipeline
+ # that ran it no longer exists.
+ raise NonRetryableException(
+ f"Job {inputs.run_id} uses pipeline version {model.pipeline_version}. Only V3 jobs can run."
+ )
+
+ attempt = current_activity_attempt()
+ if attempt > 1 and model.status in TERMINAL_JOB_STATUSES:
+ await logger.ainfo(
+ "Skipping retry - job already terminal",
+ status=model.status,
+ attempt=attempt,
+ )
+ # The consumer already finalized this run (that's how it became terminal), so the
+ # workflow must not overwrite the status or release the lock — see PipelineResult.
+ return PipelineResult(
+ should_trigger_cdp_producer=False,
+ consumer_manages_job_status=True,
+ )
# A rewrite spanning several activity budgets resumes only while live stays at the Delta
# version its checkpoint was built against, and the merge below is what moves it. Importing
@@ -982,33 +990,16 @@ async def _run(
reset_pipeline = reset_pipeline or source_response.destination_reset_required
models = await _get_models(job_inputs.run_id)
- use_v3 = models.job.pipeline_version == ExternalDataJob.PipelineVersion.V3
-
- if use_v3:
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3 import PipelineV3
-
- logger.info("Running V3 pipeline (persisted job.pipeline_version is V3)")
- pipeline: PipelineV3 | PipelineNonDLT = v3_pipeline_class(source_response)(
- source_response,
- logger,
- job_inputs.run_id,
- reset_pipeline,
- shutdown_monitor,
- resumable_source_manager,
- models=models,
- source_cursor_manager=source_cursor_manager,
- )
- else:
- pipeline = PipelineNonDLT(
- source_response,
- logger,
- job_inputs.run_id,
- reset_pipeline,
- shutdown_monitor,
- resumable_source_manager,
- models=models,
- source_cursor_manager=source_cursor_manager,
- )
+ pipeline = v3_pipeline_class(source_response)(
+ source_response,
+ logger,
+ job_inputs.run_id,
+ reset_pipeline,
+ shutdown_monitor,
+ resumable_source_manager,
+ models=models,
+ source_cursor_manager=source_cursor_manager,
+ )
result = await pipeline.run()
del pipeline
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index 543d18fe0ada..f2406199ddbc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -32,116 +32,16 @@ def _uuid7_token(age_seconds: float) -> str:
class TestCheckPipelineVersionActivity:
- @pytest.mark.parametrize(
- "ff_enabled, expected_is_v3",
- [
- (False, False),
- (True, True),
- ],
- ids=["v2", "v3"],
- )
- @patch(f"{MODULE}.is_pipeline_v3_enabled")
- @patch(f"{MODULE}.ExternalDataSource")
- @patch(f"{MODULE}.close_old_connections")
- @patch(f"{MODULE}.bind_contextvars")
- def test_returns_ff_result(
- self,
- _bind: MagicMock,
- _close: MagicMock,
- mock_source_model: MagicMock,
- mock_v3_check: MagicMock,
- ff_enabled: bool,
- expected_is_v3: bool,
- ) -> None:
- mock_source = MagicMock()
- mock_source.source_type = "Stripe"
- mock_source_model.objects.get.return_value = mock_source
- mock_v3_check.return_value = ff_enabled
-
- result = check_pipeline_version_activity(
- CheckPipelineVersionActivityInputs(team_id=TEAM_ID, source_id=SOURCE_ID)
- )
-
- assert result.is_v3 is expected_is_v3
- mock_v3_check.assert_called_once_with(TEAM_ID, "Stripe")
-
- @pytest.mark.parametrize(
- "cdc_mode, expected_is_v3",
- [
- ("streaming", True),
- ("snapshot", False),
- ],
- ids=["consumer_forces_v3", "snapshot_follows_flag"],
- )
- @patch(f"{MODULE}.is_pipeline_v3_enabled", return_value=False)
- @patch(f"{MODULE}.ExternalDataSchema")
- @patch(f"{MODULE}.ExternalDataSource")
- @patch(f"{MODULE}.close_old_connections")
- @patch(f"{MODULE}.bind_contextvars")
- def test_buffered_cdc_consumption_overrides_the_flag(
- self,
- _bind: MagicMock,
- _close: MagicMock,
- mock_source_model: MagicMock,
- mock_schema_model: MagicMock,
- _mock_v3_check: MagicMock,
- cdc_mode: str,
- expected_is_v3: bool,
- ) -> None:
- schema = MagicMock()
- schema.is_cdc = True
- schema.cdc_mode = cdc_mode
- schema.cdc_table_mode = "consolidated"
- schema.initial_sync_complete = True
- mock_schema_model.objects.filter.return_value.select_related.return_value.first.return_value = schema
- mock_source_model.objects.get.return_value = MagicMock(source_type="Postgres")
-
- result = check_pipeline_version_activity(
- CheckPipelineVersionActivityInputs(team_id=TEAM_ID, source_id=SOURCE_ID, schema_id=SCHEMA_ID)
- )
-
- assert result.is_v3 is expected_is_v3
-
- @patch(f"{MODULE}.is_pipeline_v3_enabled", return_value=True)
- @patch(f"{MODULE}.ExternalDataSchema")
- @patch(f"{MODULE}.ExternalDataSource")
- @patch(f"{MODULE}.close_old_connections")
- @patch(f"{MODULE}.bind_contextvars")
- def test_a_missing_schema_row_falls_back_to_the_flag(
- self,
- _bind: MagicMock,
- _close: MagicMock,
- mock_source_model: MagicMock,
- mock_schema_model: MagicMock,
- _mock_v3_check: MagicMock,
- ) -> None:
- mock_schema_model.objects.filter.return_value.select_related.return_value.first.return_value = None
- mock_source_model.objects.get.return_value = MagicMock(source_type="Postgres")
-
+ # Pre-patch workflow histories still schedule this activity. It must answer V3 without a
+ # database read, so a replayed run never asks for the removed V2 pipeline.
+ @pytest.mark.parametrize("schema_id", [None, SCHEMA_ID], ids=["legacy_payload", "with_schema"])
+ def test_always_returns_v3(self, schema_id: uuid.UUID | None) -> None:
result = check_pipeline_version_activity(
- CheckPipelineVersionActivityInputs(team_id=TEAM_ID, source_id=SOURCE_ID, schema_id=SCHEMA_ID)
+ CheckPipelineVersionActivityInputs(team_id=TEAM_ID, source_id=SOURCE_ID, schema_id=schema_id)
)
assert result.is_v3 is True
- @patch(f"{MODULE}.ExternalDataSource")
- @patch(f"{MODULE}.close_old_connections")
- @patch(f"{MODULE}.bind_contextvars")
- def test_source_not_found_returns_not_v3(
- self,
- _bind: MagicMock,
- _close: MagicMock,
- mock_source_model: MagicMock,
- ) -> None:
- mock_source_model.DoesNotExist = type("DoesNotExist", (Exception,), {})
- mock_source_model.objects.get.side_effect = mock_source_model.DoesNotExist
-
- result = check_pipeline_version_activity(
- CheckPipelineVersionActivityInputs(team_id=TEAM_ID, source_id=SOURCE_ID)
- )
-
- assert result.is_v3 is False
-
class TestAcquireV3PipelineLockActivity:
@pytest.mark.parametrize(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
index 4f8c3a7fe41f..5002b9b2b98d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
CreateExternalDataJobModelActivityInputs,
SourceOrSchemaDeletedError,
+ V2PipelineRemovedError,
V3PipelineLockLostError,
_build_schema_snapshot,
_create_job,
@@ -238,7 +239,7 @@ class TestCreateJob:
team_id=team.id,
source_id=schema.source_id,
schema_id=schema.id,
- pipeline_version=ExternalDataJob.PipelineVersion.V2,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
billable=True,
schema_snapshot={},
)
@@ -255,8 +256,9 @@ class TestCreateJobActivityStatusOrdering:
# job behind it can never be finalized, so it stays stuck on Running forever and blocks cancel.
@patch(f"{MODULE}.close_old_connections")
@patch(f"{MODULE}._create_job", side_effect=OperationalError("insert failed"))
+ @patch(f"{MODULE}._verify_v3_lock_still_held")
def test_schema_not_left_running_when_job_creation_fails(
- self, _mock_create: MagicMock, _mock_close_connections: MagicMock
+ self, _mock_verify_lock: MagicMock, _mock_create: MagicMock, _mock_close_connections: MagicMock
) -> None:
team = _team()
schema = _schema(team, None)
@@ -276,6 +278,22 @@ class TestCreateJobActivityStatusOrdering:
schema.refresh_from_db()
assert schema.status == ExternalDataSchema.Status.FAILED
+ # A replayed pre-patch history can still ask for a V2 job. The V2 pipeline is gone, so the
+ # run must fail before it creates a job row that no pipeline can run.
+ @patch(f"{MODULE}.close_old_connections")
+ def test_a_v2_request_fails_without_creating_a_job(self, _mock_close_connections: MagicMock) -> None:
+ team = _team()
+ schema = _schema(team, None)
+
+ with pytest.raises(V2PipelineRemovedError):
+ create_external_data_job_model_activity(
+ CreateExternalDataJobModelActivityInputs(
+ team_id=team.id, schema_id=schema.id, source_id=schema.source_id, billable=True, is_v3=False
+ )
+ )
+
+ assert not ExternalDataJob.objects.filter(schema_id=schema.id).exists()
+
@parameterized.expand([("broken", "cdc_broken"), ("paused", "cdc_extraction_paused")])
@patch(f"{MODULE}.close_old_connections")
@patch(f"{MODULE}.activity")
@@ -435,8 +453,10 @@ class TestCreateJobActivityDeletedSourceOrSchema:
@patch(f"{MODULE}.close_old_connections")
@patch(f"{MODULE}.delete_external_data_schedule")
@patch(f"{MODULE}._create_job")
+ @patch(f"{MODULE}._verify_v3_lock_still_held")
def test_integrity_error_on_insert_is_treated_as_the_same_race(
self,
+ _mock_verify_lock: MagicMock,
mock_create_job: MagicMock,
mock_delete_schedule: MagicMock,
_mock_close_connections: MagicMock,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index e70bec641782..fd6e33b5e8c5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -88,6 +88,7 @@ def _patched_activity(source_mock, model=None, schema=None):
"""Patch out every dependency import_data_activity_sync touches before source setup."""
if model is None:
model = mock.MagicMock()
+ model.pipeline_version = ExternalDataJob.PipelineVersion.V3
model.pipeline.source_type = "MongoDB"
model.pipeline.job_inputs = {}
model.folder_path = mock.Mock(return_value="dataset")
@@ -940,6 +941,7 @@ def _incremental_schema(*, is_incremental: bool, lookback_seconds: int | None) -
@contextlib.contextmanager
def _patched_activity_reaching_run(source_mock, schema, api_version=None):
model = mock.MagicMock()
+ model.pipeline_version = ExternalDataJob.PipelineVersion.V3
model.pipeline.source_type = "MongoDB"
model.pipeline.job_inputs = {}
model.pipeline.api_version = api_version
@@ -1231,6 +1233,7 @@ async def test_parent_gate_inert_for_sources_without_requirements():
def _probe_model() -> mock.MagicMock:
model = mock.MagicMock()
+ model.pipeline_version = ExternalDataJob.PipelineVersion.V3
model.pipeline.source_type = "Postgres"
model.pipeline.job_inputs = {}
model.folder_path = mock.Mock(return_value="dataset")
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py b/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py
index 3de6e10e1c56..92b4dd4d6d2b 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py
@@ -7,7 +7,7 @@ from unittest import mock
from django.conf import settings
from django.test import override_settings
-from asgiref.sync import async_to_sync
+from asgiref.sync import async_to_sync, sync_to_async
from dlt.common.configuration.specs.aws_credentials import AwsCredentials
from rest_framework.test import APIClient
from temporalio.common import RetryPolicy
@@ -30,6 +30,12 @@ from products.warehouse_sources.backend.temporal.data_imports.settings import AC
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (
SUBSCRIPTION_RESOURCE_NAME as STRIPE_SUBSCRIPTION_RESOURCE_NAME,
)
+from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.queue_replay import (
+ PostgresQueueReplay,
+ ensure_queue_tables_in_test_database,
+ patch_producer_to_test_database,
+ replay_v3_consumer,
+)
BUCKET_NAME = "test-pipeline"
@@ -98,10 +104,7 @@ def run_data_import_workflow(mock_stripe_client):
),
mock.patch("posthoganalytics.capture_exception", return_value=None),
mock.patch.object(DataWarehouseSavedQuery, "schedule_materialization"),
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock.is_pipeline_v3_enabled",
- return_value=False,
- ),
+ patch_producer_to_test_database(),
mock.patch.object(AwsCredentials, "to_session_credentials", _mock_to_session_credentials),
mock.patch.object(AwsCredentials, "to_object_store_rs_credentials", _mock_to_object_store_rs_credentials),
override_settings(
@@ -116,6 +119,7 @@ def run_data_import_workflow(mock_stripe_client):
DATAWAREHOUSE_BUCKET=BUCKET_NAME,
),
):
+ await sync_to_async(ensure_queue_tables_in_test_database)()
async with await WorkflowEnvironment.start_time_skipping() as env:
async with Worker(
env.client,
@@ -134,6 +138,8 @@ def run_data_import_workflow(mock_stripe_client):
retry_policy=RetryPolicy(maximum_attempts=1),
)
+ await replay_v3_consumer(PostgresQueueReplay(), team.id, schema.id, BUCKET_NAME)
+
run = await get_latest_run_if_exists(team_id=team.pk, pipeline_id=source.pk)
assert run is not None
assert run.status == ExternalDataJob.Status.COMPLETED, f"Workflow failed: {run.latest_error}"
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 56a906305c8a..93e977da9b48 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -767,7 +767,7 @@ class TestUpdateSyncTypeConfigKeys(BaseTest):
class TestMarkInitialSyncComplete(BaseTest):
- """The shared first-sync-complete transition (V2 pipelines + V3 loader post-load), whose
+ """The first-sync-complete transition (V3 loader post-load), whose
False→True edge is what moves a CDC schema out of snapshot mode into streaming."""
def setUp(self) -> None: