:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(warehouse-sources): move the SCD2 writer into core/delta (#76067)
estefaniaab80a345fe87
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.pyindex 0ed2195b5901..de5cbf983c6f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py@@ -1229,3 +1229,76 @@ def conditional_lru_cache_async(return wrapperreturn decorator+++def realign_decimal_buffers(table: pa.Table) -> pa.Table:+ """Re-materialize any Decimal128/256 column whose values buffer isn't 16-byte aligned.++ delta-rs (arrow-rs) aborts the entire worker — not a catchable Python exception,+ an `abort()` at the `extern "C"` boundary that can't unwind — when it's handed a+ decimal values buffer aligned to 8 bytes instead of the 16 that Rust's i128 requires.+ The misalignment arrives across the Arrow C Data Interface, which only recommends+ 8-byte alignment. Every Delta write/merge is funneled through here so a single guard+ covers both pipeline versions. See delta-io/delta-rs#3884.++ Only the values buffer (`buffers()[1]`) holds the i128 payload that must be aligned;+ the validity bitmap has no such requirement, so we don't bother checking it.++ `pa.concat_arrays` forces a fresh allocation through pyarrow's allocator (64-byte+ aligned), which satisfies the requirement. `combine_chunks()` is zero-copy and would+ keep the misaligned buffer, so it can't be used here. The buffer scan is cheap and+ the copy only fires on the rare misaligned batch, so the common path is untouched.+ """+ new_columns: dict[str, pa.ChunkedArray] = {}+ realigned = False+ for i in range(table.num_columns):+ field = table.field(i)+ column = table.column(i)+ if pa.types.is_decimal(field.type) and any(+ (values := chunk.buffers()[1]) is not None and values.address % 16 for chunk in column.chunks+ ):+ # concat_arrays preserves the chunks' (decimal) type; pyarrow-stubs has no+ # chunked_array overload for an explicit decimal type=.+ new_columns[field.name] = pa.chunked_array([pa.concat_arrays(column.chunks)])+ realigned = True+ else:+ new_columns[field.name] = column++ if not realigned:+ return table++ return pa.table(new_columns, schema=table.schema)+++def first_per_pk_table(pa_table: pa.Table, pk_columns: list[str], keep: Literal["first", "last"] = "first") -> pa.Table:+ """Return a table containing only one row per PK tuple (in original row order).++ `keep` picks which occurrence survives: "first" is used when closing existing+ "current" rows during SCD2 append; "last" is used to dedupe upsert batches, where+ the latest occurrence of a key carries the freshest data. Either way the merge+ receives at most one source row per key, avoiding ambiguous multi-match merge+ semantics (and the duplicate inserts `when_not_matched_insert_all` would produce).+ """+ if not pk_columns or pa_table.num_rows == 0:+ return pa_table++ # Strategy: tag every row with its position, group by PK, and for each PK+ # take the smallest (or largest) position — the first (or last) time we saw+ # that PK. Sorting those positions at the end restores the original row order.+ #+ # We use numpy for the final sort because pyarrow's type stubs for+ # `pc.sort_indices` / `Array.take` are currently broken — numpy's stubs work.+ idx_col_name = "__ph_cdc_row_idx"+ aggregate: Literal["min", "max"] = "min" if keep == "first" else "max"++ # 1. Add a row-position column: [0, 1, 2, ..., n-1]+ indexed = pa_table.append_column(idx_col_name, pa.array(range(pa_table.num_rows), type=pa.int64()))++ # 2. Group by PK, keeping only one position per PK+ grouped = indexed.group_by(pk_columns).aggregate([(idx_col_name, aggregate)])++ # 3. Sort those positions ascending so the output mirrors the input row order+ kept_indices = np.sort(grouped.column(f"{idx_col_name}_{aggregate}").to_numpy())++ # 4. Materialize the rows at those positions from the original table+ return pa_table.take(kept_indices)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/evolution.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/evolution.pynew file mode 100644index 000000000000..6083b5a23c64--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/evolution.py@@ -0,0 +1,34 @@+import asyncio++import pyarrow as pa+import deltalake+from dlt.common.libs.deltalake import ensure_delta_compatible_arrow_schema++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (+ pyarrow_schema_from_arrow_exportable,+)+++async def evolve_delta_schema(delta_table: deltalake.DeltaTable, schema: pa.Schema) -> deltalake.DeltaTable:+ """Add any columns `schema` carries that the table doesn't have yet.++ Kept out of `delta/ops.py` so the `dlt` import stays off the maintenance-only import path.++ Columns added here always predate their own addition: every file the table already+ holds was written without this column, so it must tolerate absent values on those+ rows. Forcing nullable regardless of the incoming batch's own nullability (which+ reflects only whether *this* batch happened to contain nulls) is what lets a later+ `optimize.compact()` read those old files at all — a non-nullable add otherwise fails+ compaction with "Non-nullable column '<name>' is missing from the physical schema".+ """+ delta_table_schema = pyarrow_schema_from_arrow_exportable(delta_table.schema())++ new_fields = [+ deltalake.Field.from_arrow(field.with_nullable(True))+ for field in ensure_delta_compatible_arrow_schema(schema)+ if field.name not in delta_table_schema.names+ ]+ if new_fields:+ await asyncio.to_thread(delta_table.alter.add_columns, new_fields)++ return delta_tablediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.pyindex 30f3950fca18..907eec5b2e67 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/ops.py@@ -1,10 +1,31 @@import asynciofrom collections.abc import Callable+from django.conf import settings+import deltalakeimport deltalake.exceptionsfrom structlog.types import FilteringBoundLogger++def delta_merge_spill_kwargs() -> dict[str, int]:+ """delta-rs `merge` kwargs that let DataFusion spill to disk instead of OOMing on large merges.++ A merge decompresses the target partition into an Arrow working set that can exceed the pod's+ memory limit and take down every co-tenant activity. When the byte budgets are configured (and the+ worker mounts a scratch disk at its TMPDIR), delta-rs bounds DataFusion's memory pool: bytes past+ `max_spill_size` spill to disk, capped at `max_temp_directory_size`. Unset → omit the kwargs so+ DataFusion keeps its unbounded default (today's behavior), which also keeps this compatible with+ deltalake versions predating the parameters.+ """+ kwargs: dict[str, int] = {}+ if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES is not None:+ kwargs["max_spill_size"] = settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES+ if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES is not None:+ kwargs["max_temp_directory_size"] = settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES+ return kwargs++# Delta's conflict checker raises CommitFailedError the moment a concurrent commit invalidates what# a committing operation read — a merge predicate, or optimize.compact's file-rewrite plan — unlike a# plain version-bump race, delta-rs does not consume max_commit_retries or retry this itself (seediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.pynew file mode 100644index 000000000000..73b3e36732c8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/scd2.py@@ -0,0 +1,138 @@+import json+import asyncio+from collections.abc import Sequence+from typing import TYPE_CHECKING, Any++import pyarrow as pa+import deltalake++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (+ first_per_pk_table,+ normalize_column_name,+ realign_decimal_buffers,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.evolution import evolve_delta_schema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (+ delta_merge_spill_kwargs,+ execute_with_conflict_retry,+)++if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import (+ DeltaTableHelper,+ )+++class Scd2DeltaWriter:+ """SCD Type 2 writer over one schema's Delta table.++ Stateless over a `DeltaTableHelper`, which holds the cached table handle — construct one at+ the call site. The validity-interval column names are injected so the writer stays generic;+ today's only caller is the CDC load path, which passes the columns `cdc/batcher.py` stamps+ via `build_scd2_table`.+ """++ def __init__(self, table: "DeltaTableHelper", *, valid_from_column: str, valid_to_column: str) -> None:+ self._table = table+ self._logger = table.logger+ self._valid_from_column = valid_from_column+ self._valid_to_column = valid_to_column++ async def write(+ self,+ data: pa.Table,+ primary_keys: Sequence[Any],+ commit_metadata: dict[str, str] | None = None,+ ) -> deltalake.DeltaTable:+ """Write SCD Type 2 data: close existing current rows, then append new rows.++ For each PK that appears in `data`:+ 1. Find the existing row in the target with matching PK and valid_to IS NULL+ (the current row) and update its valid_to to the earliest valid_from of the+ new events for that PK.+ 2. Append all rows from `data` as new history entries.++ `data` is expected to already carry the valid_from / valid_to columns.+ """+ # See realign_decimal_buffers. The close-existing merge uses first_per_pk_table(data),+ # whose take() output is freshly allocated, so realigning `data` here covers both the+ # close and the append.+ data = realign_decimal_buffers(data)++ delta_table = await self._table.get_delta_table()++ if delta_table:+ delta_table = await evolve_delta_schema(delta_table, data.schema)++ commit_properties: deltalake.CommitProperties | None = (+ deltalake.CommitProperties(custom_metadata=commit_metadata) if commit_metadata else None+ )++ # Step 1: Close existing current rows for PKs in this batch+ if delta_table is not None and primary_keys and self._valid_from_column in data.column_names:+ existing_delta_table = delta_table+ py_column_names = data.column_names+ normalized_pks: list[str] = []+ for x in primary_keys:+ n = normalize_column_name(x)+ if n in py_column_names:+ normalized_pks.append(n)++ if normalized_pks:+ # Use only the first row per PK to avoid ambiguous multi-match merge+ first_per_pk = first_per_pk_table(data, normalized_pks)++ predicate_parts = [f"source.{col} = target.{col}" for col in normalized_pks]+ predicate_parts.append(f"target.{self._valid_to_column} IS NULL")+ predicate = " AND ".join(predicate_parts)++ # NOTE: do NOT tag this intermediate merge with `commit_properties`. SCD2 is a+ # two-step write (close-existing then append-new); if we tagged step 1 with the+ # same (run_uuid, batch_index) and the process crashed before step 2, Kafka+ # redelivery would see the tagged commit, treat the batch as already done, and+ # silently skip the append → data loss. Tag only the terminal commit (step 2).+ def _do_scd2_close(first_per_pk: pa.Table, predicate: str) -> dict:+ return (+ existing_delta_table.merge(+ source=first_per_pk,+ source_alias="source",+ target_alias="target",+ predicate=predicate,+ streamed_exec=False,+ **delta_merge_spill_kwargs(),+ )+ .when_matched_update(updates={self._valid_to_column: f"source.{self._valid_from_column}"})+ .execute()+ )++ close_stats = await execute_with_conflict_retry(+ existing_delta_table,+ lambda: _do_scd2_close(first_per_pk, predicate),+ "Scd2DeltaWriter.write: close merge",+ self._logger,+ )+ await self._logger.adebug(f"SCD2 close stats: {json.dumps(close_stats)}")++ # Step 2: Append all new rows+ if delta_table is None:+ storage_options = self._table.get_storage_options()+ delta_uri = await self._table.get_table_uri()+ delta_table = await asyncio.to_thread(+ deltalake.DeltaTable.create,+ table_uri=delta_uri,+ schema=data.schema,+ storage_options=storage_options,+ )++ await asyncio.to_thread(+ deltalake.write_deltalake,+ table_or_uri=delta_table,+ data=data,+ mode="append",+ schema_mode="merge",+ commit_properties=commit_properties,+ )++ delta_table = await self._table.get_delta_table()+ assert delta_table is not None+ return delta_tablediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.pyindex 3aff814569ae..e0ff57ccae5f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_ops.py@@ -1,10 +1,14 @@import pytestfrom unittest.mock import AsyncMock, MagicMock+from django.test import override_settings+import deltalake+from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (DELTA_MERGE_CONFLICT_RETRIES,+ delta_merge_spill_kwargs,execute_with_conflict_retry,)@@ -13,6 +17,32 @@ def _make_logger():return MagicMock(adebug=AsyncMock(), ainfo=AsyncMock(), awarning=AsyncMock(), aerror=AsyncMock())+class TestDeltaMergeSpillKwargs:+ # Guards the wiring from settings → delta-rs merge kwargs. A silent break here (renamed setting,+ # dropped forwarding, or emitting a None kwarg) stops merges spilling to disk and OOMs return.+ @parameterized.expand(+ [+ ("both_unset", None, None, {}),+ ("only_spill", 6_442_450_944, None, {"max_spill_size": 6_442_450_944}),+ ("only_temp_dir", None, 51_539_607_552, {"max_temp_directory_size": 51_539_607_552}),+ (+ "both_set",+ 6_442_450_944,+ 51_539_607_552,+ {"max_spill_size": 6_442_450_944, "max_temp_directory_size": 51_539_607_552},+ ),+ ]+ )+ def test_kwargs_from_settings(+ self, _case: str, spill: int | None, temp_dir: int | None, expected: dict[str, int]+ ) -> None:+ with override_settings(+ DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES=spill,+ DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES=temp_dir,+ ):+ assert delta_merge_spill_kwargs() == expected++class TestExecuteWithConflictRetry:"""A committing operation's CommitFailedError means delta-rs's conflict checker rejected thecommit outright, without spending any of its own internal retry budget (see the comment ondiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.pynew file mode 100644index 000000000000..1441932481e6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_scd2.py@@ -0,0 +1,102 @@+from datetime import UTC, datetime+from decimal import Decimal+from pathlib import Path++import pytest++import pyarrow as pa+import deltalake+import pyarrow.compute as pc++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.scd2 import Scd2DeltaWriter+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import DeltaTableHelper+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.test.test_delta_table_helper import (+ _decimal_array,+ _make_local_helper,+ _table_is_misaligned,+)++_TS_TYPE = pa.timestamp("us", tz="UTC")+++def _make_writer(delta_uri: str) -> Scd2DeltaWriter:+ return Scd2DeltaWriter(_make_local_helper(delta_uri), valid_from_column="valid_from", valid_to_column="valid_to")+++class TestScd2Write:+ @pytest.mark.asyncio+ async def test_write_misaligned_decimal_to_local_delta(self, tmp_path: Path) -> None:+ # The SCD2 write carries its own realignment guard; without it the+ # close-existing merge would hand delta-rs a misaligned decimal and abort the worker.+ delta_path = str(tmp_path / "scd2_table")+ ts1 = datetime(2026, 1, 1, tzinfo=UTC)+ ts2 = datetime(2026, 2, 1, tzinfo=UTC)+ # Seed a current (valid_to IS NULL) row for id=1 so the new batch closes it.+ deltalake.write_deltalake(+ delta_path,+ pa.table(+ {+ "id": pa.array([1]),+ "amount": _decimal_array([5], misaligned=False),+ "valid_from": pa.array([ts1], type=_TS_TYPE),+ "valid_to": pa.array([None], type=_TS_TYPE),+ }+ ),+ )++ batch = pa.table(+ {+ "id": pa.array([1]),+ "amount": _decimal_array([7], misaligned=True),+ "valid_from": pa.array([ts2], type=_TS_TYPE),+ "valid_to": pa.array([None], type=_TS_TYPE),+ }+ )+ assert _table_is_misaligned(batch) is True++ result = await _make_writer(delta_path).write(data=batch, primary_keys=["id"])++ final = result.to_pyarrow_table()+ # The seeded row is closed (valid_to set) and the new misaligned row is appended.+ assert final.num_rows == 2+ assert set(final.column("amount").to_pylist()) == {5, 7}+ closed = final.filter(pc.equal(final.column("amount"), pa.scalar(Decimal("5.00"), type=pa.decimal128(10, 2))))+ assert closed.column("valid_to").to_pylist() == [ts2]++ @pytest.mark.asyncio+ async def test_only_terminal_append_commit_carries_metadata(self, tmp_path: Path) -> None:+ # SCD2 is a two-step write (close-existing merge, then append). If the intermediate+ # close merge were tagged with (run_uuid, batch_index) and the writer crashed before+ # the append, Kafka redelivery would find the tagged commit via+ # has_batch_been_committed, treat the batch as already written, and silently skip+ # the append — data loss. Only the terminal append commit may carry the metadata.+ delta_path = str(tmp_path / "scd2_table")+ ts1 = datetime(2026, 1, 1, tzinfo=UTC)+ ts2 = datetime(2026, 2, 1, tzinfo=UTC)+ deltalake.write_deltalake(+ delta_path,+ pa.table(+ {+ "id": pa.array([1]),+ "valid_from": pa.array([ts1], type=_TS_TYPE),+ "valid_to": pa.array([None], type=_TS_TYPE),+ }+ ),+ )+ batch = pa.table(+ {+ "id": pa.array([1]),+ "valid_from": pa.array([ts2], type=_TS_TYPE),+ "valid_to": pa.array([None], type=_TS_TYPE),+ }+ )+ metadata = {"run_uuid": "r1", "batch_index": "0"}++ await _make_writer(delta_path).write(data=batch, primary_keys=["id"], commit_metadata=metadata)++ history = deltalake.DeltaTable(delta_path).history()+ # Newest first: [append (WRITE), close (MERGE), seed (WRITE)]. _commit_matches is the+ # same layout-agnostic check has_batch_been_committed uses for redelivery dedup.+ tagged = [c["operation"] for c in history if DeltaTableHelper._commit_matches(c, metadata)]+ assert tagged == ["WRITE"]+ assert any(c["operation"] == "MERGE" for c in history)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.pyindex 042e06dcdce9..ebcf00292fe0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta_table_helper.py@@ -7,12 +7,10 @@ from typing import Any, Literalfrom django.conf import settings-import numpy as npimport pyarrow as paimport deltalake as deltalakeimport pyarrow.compute as pcimport deltalake.exceptions-from dlt.common.libs.deltalake import ensure_delta_compatible_arrow_schemafrom structlog.types import FilteringBoundLoggerfrom posthog.exceptions_capture import capture_exception@@ -24,14 +22,17 @@ from products.warehouse_sources.backend.temporal.data_imports.naming_conventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (align_incoming_decimals_to_delta,conditional_lru_cache_async,+ first_per_pk_table,normalize_column_name,- pyarrow_schema_from_arrow_exportable,+ realign_decimal_buffers,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (is_transient_object_store_error,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.evolution import evolve_delta_schemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (+ delta_merge_spill_kwargs,execute_with_conflict_retry,)@@ -40,24 +41,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del_PURGE_S3_PREFIX_MAX_ATTEMPTS = 4-def _delta_merge_spill_kwargs() -> dict[str, int]:- """delta-rs `merge` kwargs that let DataFusion spill to disk instead of OOMing on large merges.-- A merge decompresses the target partition into an Arrow working set that can exceed the pod's- memory limit and take down every co-tenant activity. When the byte budgets are configured (and the- worker mounts a scratch disk at its TMPDIR), delta-rs bounds DataFusion's memory pool: bytes past- `max_spill_size` spill to disk, capped at `max_temp_directory_size`. Unset → omit the kwargs so- DataFusion keeps its unbounded default (today's behavior), which also keeps this compatible with- deltalake versions predating the parameters.- """- kwargs: dict[str, int] = {}- if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES is not None:- kwargs["max_spill_size"] = settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES- if settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES is not None:- kwargs["max_temp_directory_size"] = settings.DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES- return kwargs--async def _purge_s3_prefix(s3: Any, uri: str) -> None:"""Delete every object under `uri`, retrying on transient S3 SlowDown throttling.@@ -117,81 +100,6 @@ def _write_deltalake()-def _realign_decimal_buffers(table: pa.Table) -> pa.Table:- """Re-materialize any Decimal128/256 column whose values buffer isn't 16-byte aligned.-- delta-rs (arrow-rs) aborts the entire worker — not a catchable Python exception,- an `abort()` at the `extern "C"` boundary that can't unwind — when it's handed a- decimal values buffer aligned to 8 bytes instead of the 16 that Rust's i128 requires.- The misalignment arrives across the Arrow C Data Interface, which only recommends- 8-byte alignment. We funnel every Delta write/merge through here so a single guard- covers both pipeline versions. See delta-io/delta-rs#3884.-- Only the values buffer (`buffers()[1]`) holds the i128 payload that must be aligned;- the validity bitmap has no such requirement, so we don't bother checking it.-- `pa.concat_arrays` forces a fresh allocation through pyarrow's allocator (64-byte- aligned), which satisfies the requirement. `combine_chunks()` is zero-copy and would- keep the misaligned buffer, so it can't be used here. The buffer scan is cheap and- the copy only fires on the rare misaligned batch, so the common path is untouched.- """- new_columns: dict[str, pa.ChunkedArray] = {}- realigned = False- for i in range(table.num_columns):- field = table.field(i)- column = table.column(i)- if pa.types.is_decimal(field.type) and any(- (values := chunk.buffers()[1]) is not None and values.address % 16 for chunk in column.chunks- ):- # concat_arrays preserves the chunks' (decimal) type; pyarrow-stubs has no- # chunked_array overload for an explicit decimal type=.- new_columns[field.name] = pa.chunked_array([pa.concat_arrays(column.chunks)])- realigned = True- else:- new_columns[field.name] = column-- if not realigned:- return table-- return pa.table(new_columns, schema=table.schema)---def _first_per_pk_table(- pa_table: pa.Table, pk_columns: list[str], keep: Literal["first", "last"] = "first"-) -> pa.Table:- """Return a table containing only one row per PK tuple (in original row order).-- `keep` picks which occurrence survives: "first" is used when closing existing- "current" rows during SCD2 append; "last" is used to dedupe upsert batches, where- the latest occurrence of a key carries the freshest data. Either way the merge- receives at most one source row per key, avoiding ambiguous multi-match merge- semantics (and the duplicate inserts `when_not_matched_insert_all` would produce).- """- if not pk_columns or pa_table.num_rows == 0:- return pa_table-- # Strategy: tag every row with its position, group by PK, and for each PK- # take the smallest (or largest) position — the first (or last) time we saw- # that PK. Sorting those positions at the end restores the original row order.- #- # We use numpy for the final sort because pyarrow's type stubs for- # `pc.sort_indices` / `Array.take` are currently broken — numpy's stubs work.- idx_col_name = "__ph_cdc_row_idx"- aggregate: Literal["min", "max"] = "min" if keep == "first" else "max"-- # 1. Add a row-position column: [0, 1, 2, ..., n-1]- indexed = pa_table.append_column(idx_col_name, pa.array(range(pa_table.num_rows), type=pa.int64()))-- # 2. Group by PK, keeping only one position per PK- grouped = indexed.group_by(pk_columns).aggregate([(idx_col_name, aggregate)])-- # 3. Sort those positions ascending so the output mirrors the input row order- kept_indices = np.sort(grouped.column(f"{idx_col_name}_{aggregate}").to_numpy())-- # 4. Materialize the rows at those positions from the original table- return pa_table.take(kept_indices)--def _merge_predicate_ops(normalized_primary_keys: list[str]) -> list[str]:"""Per-key merge match conditions, using NULL-safe equality.@@ -201,7 +109,7 @@ def _merge_predicate_ops(normalized_primary_keys: list[str]) -> list[str]:`segments.device`, which are frequently NULL — therefore never match their existing target row,so `when_not_matched_insert_all` re-inserts them on *every* incremental sync and the tablesilently accumulates a duplicate per NULL-keyed row. `IS NOT DISTINCT FROM` treats NULL == NULL,- matching the source dedup (`_first_per_pk_table` groups NULLs together) and stopping the drift.+ matching the source dedup (`first_per_pk_table` groups NULLs together) and stopping the drift.Each term is parenthesised: delta-rs's predicate parser (1.6.1) mis-associates a bare`a IS NOT DISTINCT FROM b AND c IS NOT DISTINCT FROM d` (it groups `b AND c`), so the parens are@@ -328,29 +236,6 @@ class DeltaTableHelper:else:capture_exception(e)- async def _evolve_delta_schema(self, schema: pa.Schema) -> deltalake.DeltaTable:- delta_table = await self.get_delta_table()- if delta_table is None:- raise Exception("Deltalake table not found")-- delta_table_schema = pyarrow_schema_from_arrow_exportable(delta_table.schema())-- # Columns added here always predate their own addition: every file the table already- # holds was written without this column, so it must tolerate absent values on those- # rows. Forcing nullable regardless of the incoming batch's own nullability (which- # reflects only whether *this* batch happened to contain nulls) is what lets a later- # `optimize.compact()` read those old files at all — a non-nullable add otherwise fails- # compaction with "Non-nullable column '<name>' is missing from the physical schema".- new_fields = [- deltalake.Field.from_arrow(field.with_nullable(True))- for field in ensure_delta_compatible_arrow_schema(schema)- if field.name not in delta_table_schema.names- ]- if new_fields:- await asyncio.to_thread(delta_table.alter.add_columns, new_fields)-- return delta_table-@conditional_lru_cache_async(maxsize=1, condition=lambda result: result is not None)async def get_delta_table(self) -> deltalake.DeltaTable | None:delta_uri = await self._get_delta_table_uri()@@ -451,7 +336,7 @@ class DeltaTableHelper:if use_partitioning:dedupe_keys.append(PARTITION_KEY)- deduped = _first_per_pk_table(data, dedupe_keys, keep="last")+ deduped = first_per_pk_table(data, dedupe_keys, keep="last")dropped = data.num_rows - deduped.num_rowsif dropped > 0:await self._logger.awarning(@@ -569,14 +454,14 @@ class DeltaTableHelper:commit_metadata: dict[str, str] | None = None,) -> deltalake.DeltaTable:# Guard against delta-rs aborting the worker on misaligned decimal buffers (see- # _realign_decimal_buffers). Sub-tables derived below via filter()/take() are+ # realign_decimal_buffers). Sub-tables derived below via filter()/take() are# freshly allocated by pyarrow and so inherit safe alignment.- data = _realign_decimal_buffers(data)+ data = realign_decimal_buffers(data)delta_table = await self.get_delta_table()if delta_table:- delta_table = await self._evolve_delta_schema(data.schema)+ delta_table = await evolve_delta_schema(delta_table, data.schema)await self._logger.adebug(f"write_to_deltalake: _is_first_sync = {self._is_first_sync}. should_overwrite_table = {should_overwrite_table}"@@ -682,7 +567,7 @@ class DeltaTableHelper:predicate=predicate,streamed_exec=True,commit_properties=merge_commit_properties,- **_delta_merge_spill_kwargs(),+ **delta_merge_spill_kwargs(),).when_matched_update_all().when_not_matched_insert_all()@@ -708,7 +593,7 @@ class DeltaTableHelper:predicate=" AND ".join(predicate_ops),streamed_exec=False,commit_properties=commit_properties,- **_delta_merge_spill_kwargs(),+ **delta_merge_spill_kwargs(),).when_matched_update_all().when_not_matched_insert_all()@@ -805,106 +690,6 @@ class DeltaTableHelper:return delta_table- async def write_scd2_to_deltalake(- self,- data: pa.Table,- primary_keys: Sequence[Any],- commit_metadata: dict[str, str] | None = None,- ) -> deltalake.DeltaTable:- """Write CDC SCD Type 2 data: close existing current rows, then append new rows.-- For each PK that appears in `data`:- 1. Find the existing row in the target with matching PK and valid_to IS NULL- (the current row) and update its valid_to to the earliest valid_from of the- new events for that PK.- 2. Append all rows from `data` as new history entries.-- `data` is expected to already have valid_from / valid_to columns as produced- by batcher.build_scd2_table().- """- # See write_to_deltalake / _realign_decimal_buffers. The close-existing merge uses- # _first_per_pk_table(data), whose take() output is freshly allocated, so realigning- # `data` here covers both the close and the append.- data = _realign_decimal_buffers(data)-- delta_table = await self.get_delta_table()-- if delta_table:- delta_table = await self._evolve_delta_schema(data.schema)-- commit_properties: deltalake.CommitProperties | None = (- deltalake.CommitProperties(custom_metadata=commit_metadata) if commit_metadata else None- )-- # Step 1: Close existing current rows for PKs in this batch- if delta_table is not None and primary_keys and "valid_from" in data.column_names:- existing_delta_table = delta_table- py_column_names = data.column_names- normalized_pks: list[str] = []- for x in primary_keys:- n = normalize_column_name(x)- if n in py_column_names:- normalized_pks.append(n)-- if normalized_pks:- # Use only the first row per PK to avoid ambiguous multi-match merge- first_per_pk = _first_per_pk_table(data, normalized_pks)-- predicate_parts = [f"source.{col} = target.{col}" for col in normalized_pks]- predicate_parts.append("target.valid_to IS NULL")- predicate = " AND ".join(predicate_parts)-- # NOTE: do NOT tag this intermediate merge with `commit_properties`. SCD2 is a- # two-step write (close-existing then append-new); if we tagged step 1 with the- # same (run_uuid, batch_index) and the process crashed before step 2, Kafka- # redelivery would see the tagged commit, treat the batch as already done, and- # silently skip the append → data loss. Tag only the terminal commit (step 2).- def _do_scd2_close(first_per_pk: pa.Table, predicate: str) -> dict:- return (- existing_delta_table.merge(- source=first_per_pk,- source_alias="source",- target_alias="target",- predicate=predicate,- streamed_exec=False,- **_delta_merge_spill_kwargs(),- )- .when_matched_update(updates={"valid_to": "source.valid_from"})- .execute()- )-- close_stats = await execute_with_conflict_retry(- existing_delta_table,- lambda: _do_scd2_close(first_per_pk, predicate),- "write_scd2_to_deltalake: close merge",- self._logger,- )- await self._logger.adebug(f"SCD2 close stats: {json.dumps(close_stats)}")-- # Step 2: Append all new rows- if delta_table is None:- storage_options = self._get_credentials()- delta_uri = await self._get_delta_table_uri()- delta_table = await asyncio.to_thread(- deltalake.DeltaTable.create,- table_uri=delta_uri,- schema=data.schema,- storage_options=storage_options,- )-- await asyncio.to_thread(- deltalake.write_deltalake,- table_or_uri=delta_table,- data=data,- mode="append",- schema_mode="merge",- commit_properties=commit_properties,- )-- delta_table = await self.get_delta_table()- assert delta_table is not None- return delta_table-async def has_commit_with_metadata(self, match: dict[str, str], *, scan_limit: int = 50) -> bool:"""Check whether any recent delta commit has custom metadata matching all entries in `match`.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.pyindex 61a741296893..4ce45e0031eb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py@@ -31,12 +31,12 @@ from structlog.types import FilteringBoundLoggerfrom products.data_warehouse.backend.facade.api import aget_s3_clientfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import normalize_column_name-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import (- _purge_s3_prefix,- _realign_decimal_buffers,+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (+ normalize_column_name,+ realign_decimal_buffers,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import _purge_s3_prefixfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (append_partition_key_to_table,)@@ -427,7 +427,7 @@ async def _rewrite_into_temp(partition_keys=used_keys,)- partitioned_table = _realign_decimal_buffers(partitioned_table)+ partitioned_table = realign_decimal_buffers(partitioned_table)await asyncio.to_thread(deltalake.write_deltalake,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.pyindex 9a747c5763d8..bba2d6fcd681 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_delta_table_helper.py@@ -1,5 +1,4 @@import json-from datetime import UTC, datetimefrom decimal import Decimalfrom pathlib import Pathfrom types import SimpleNamespace@@ -18,18 +17,19 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (SchemaColumnTypeChangedException,evolve_pyarrow_schema,+ first_per_pk_table,+ realign_decimal_buffers,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenancefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import (DeltaTableHelper,- _delta_merge_spill_kwargs,_deltalite_write_stats,- _first_per_pk_table,_merge_predicate_ops,- _realign_decimal_buffers,)+_HELPER_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper"+def _decimal_array(values: list, *, precision: int = 10, scale: int = 2, misaligned: bool) -> pa.Array:"""Build a Decimal128 array. When `misaligned`, its data buffer is 8-byte but NOT@@ -171,32 +171,6 @@ class TestStorageOptionsCommitSafety:assert ("AWS_S3_ALLOW_UNSAFE_RENAME" in options) is allow_unsafe-class TestDeltaMergeSpillKwargs:- # Guards the wiring from settings → delta-rs merge kwargs. A silent break here (renamed setting,- # dropped forwarding, or emitting a None kwarg) stops merges spilling to disk and OOMs return.- @parameterized.expand(- [- ("both_unset", None, None, {}),- ("only_spill", 6_442_450_944, None, {"max_spill_size": 6_442_450_944}),- ("only_temp_dir", None, 51_539_607_552, {"max_temp_directory_size": 51_539_607_552}),- (- "both_set",- 6_442_450_944,- 51_539_607_552,- {"max_spill_size": 6_442_450_944, "max_temp_directory_size": 51_539_607_552},- ),- ]- )- def test_kwargs_from_settings(- self, _case: str, spill: int | None, temp_dir: int | None, expected: dict[str, int]- ) -> None:- with override_settings(- DATA_WAREHOUSE_DELTA_MERGE_MAX_SPILL_SIZE_BYTES=spill,- DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES=temp_dir,- ):- assert _delta_merge_spill_kwargs() == expected--class TestHasCommitWithMetadata:@pytest.mark.asyncioasync def test_returns_false_when_no_delta_table(self, helper: DeltaTableHelper):@@ -365,7 +339,7 @@ class TestWriteToDeltalakeCommitMetadataPassThrough:with (patch.object(helper, "get_delta_table", AsyncMock(return_value=mock_delta)),- patch.object(helper, "_evolve_delta_schema", AsyncMock(return_value=mock_delta)),+ patch(f"{_HELPER_MODULE}.evolve_delta_schema", AsyncMock(return_value=mock_delta)),patch("deltalake.write_deltalake") as mock_write,):await helper.write_to_deltalake(@@ -656,7 +630,7 @@ class TestIncrementalBatchDeduplication:def test_first_per_pk_table_keep_modes(self, _name, keep, expected_names):table = pa.table({"id": [1, 1, 2], "name": ["a1", "a2", "b1"]})- result = _first_per_pk_table(table, ["id"], keep=keep).sort_by("id")+ result = first_per_pk_table(table, ["id"], keep=keep).sort_by("id")assert result.column("id").to_pylist() == [1, 2]assert result.column("name").to_pylist() == expected_names@@ -773,7 +747,7 @@ class TestRealignDecimalBuffers:table = pa.table({"amount": _decimal_array([1, 2, 3, 4], misaligned=True), "id": pa.array([1, 2, 3, 4])})assert _table_is_misaligned(table) is True- result = _realign_decimal_buffers(table)+ result = realign_decimal_buffers(table)assert _table_is_misaligned(result) is False# Values and schema are preserved exactly@@ -792,7 +766,7 @@ class TestRealignDecimalBuffers:def test_unmisaligned_table_is_returned_unchanged(self, table: pa.Table) -> None:assert _table_is_misaligned(table) is False- result = _realign_decimal_buffers(table)+ result = realign_decimal_buffers(table)# No misalignment found → identity return (no needless copy)assert result is table@@ -802,7 +776,7 @@ class TestRealignDecimalBuffers:misaligned_dec = _decimal_array([30, 40], misaligned=True)table = pa.table({"good": aligned_dec, "bad": misaligned_dec, "id": pa.array([1, 2])})- result = _realign_decimal_buffers(table)+ result = realign_decimal_buffers(table)assert _table_is_misaligned(result) is Falseassert result.column("good").to_pylist() == [10, 20]@@ -822,7 +796,7 @@ class TestRealignDecimalBuffers:table = pa.table({"amount": chunked, "id": pa.array([1, 2, 3, 4])})assert _table_is_misaligned(table) is True- result = _realign_decimal_buffers(table)+ result = realign_decimal_buffers(table)assert _table_is_misaligned(result) is Falseassert result.column("amount").to_pylist() == [1, 2, 3, 4]@@ -830,7 +804,7 @@ class TestRealignDecimalBuffers:def test_empty_decimal_table(self) -> None:table = pa.table({"amount": pa.array([], type=pa.decimal128(10, 2)), "id": pa.array([], type=pa.int64())})- result = _realign_decimal_buffers(table)+ result = realign_decimal_buffers(table)assert result.num_rows == 0assert result.schema == table.schema@@ -874,47 +848,6 @@ class TestWriteMisalignedDecimalEndToEnd:assert {3, 4}.issubset(set(final.column("id").to_pylist()))assert {7, 8}.issubset(amounts)- @pytest.mark.asyncio- async def test_write_scd2_misaligned_decimal_to_local_delta(self, tmp_path: Path) -> None:- # write_scd2_to_deltalake carries its own realignment guard; without it the- # close-existing merge would hand delta-rs a misaligned decimal and abort the worker.- delta_path = str(tmp_path / "scd2_table")- ts1 = datetime(2026, 1, 1, tzinfo=UTC)- ts2 = datetime(2026, 2, 1, tzinfo=UTC)- ts_type = pa.timestamp("us", tz="UTC")- # Seed a current (valid_to IS NULL) row for id=1 so the new batch closes it.- deltalake.write_deltalake(- delta_path,- pa.table(- {- "id": pa.array([1]),- "amount": _decimal_array([5], misaligned=False),- "valid_from": pa.array([ts1], type=ts_type),- "valid_to": pa.array([None], type=ts_type),- }- ),- )-- helper = _make_local_helper(delta_path)- batch = pa.table(- {- "id": pa.array([1]),- "amount": _decimal_array([7], misaligned=True),- "valid_from": pa.array([ts2], type=ts_type),- "valid_to": pa.array([None], type=ts_type),- }- )- assert _table_is_misaligned(batch) is True-- result = await helper.write_scd2_to_deltalake(data=batch, primary_keys=["id"])-- final = result.to_pyarrow_table()- # The seeded row is closed (valid_to set) and the new misaligned row is appended.- assert final.num_rows == 2- assert set(final.column("amount").to_pylist()) == {5, 7}- closed = final.filter(pc.equal(final.column("amount"), pa.scalar(Decimal("5.00"), type=pa.decimal128(10, 2))))- assert closed.column("valid_to").to_pylist() == [ts2]-class TestIsTableCorrupted:_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper"diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex bdd08e238a3a..77ac295dcf20 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.models.external_data_schema import Exterfrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (CDC_OP_COLUMN,+ SCD2_VALID_FROM_COLUMN,SCD2_VALID_TO_COLUMN,TOAST_OMITTED_COLUMN,enrich_delete_rows,@@ -38,6 +39,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrpyarrow_schema_from_arrow_exportable,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.scd2 import Scd2DeltaWriterfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta_table_helper import DeltaTableHelperfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.hogql_schema import HogQLSchemafrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (@@ -784,7 +786,12 @@ def process_message(with DELTA_WRITE_DURATION_SECONDS.labels(team_id=team_id_str, schema_id=schema_id_str, write_type="scd2_append").time():- delta_table = async_to_sync(delta_table_helper.write_scd2_to_deltalake)(+ scd2_writer = Scd2DeltaWriter(+ delta_table_helper,+ valid_from_column=SCD2_VALID_FROM_COLUMN,+ valid_to_column=SCD2_VALID_TO_COLUMN,+ )+ delta_table = async_to_sync(scd2_writer.write)(data=pa_table,primary_keys=primary_keys or [],commit_metadata=commit_metadata,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.pyindex b9c4f4549d78..333bf9d0164d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py@@ -231,6 +231,7 @@ class TestProcessMessageOwnershipGate:@patch(f"{_PROCESSOR}.posthoganalytics")@patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))@patch(f"{_PROCESSOR}.is_batch_already_processed", return_value=False)+ @patch(f"{_PROCESSOR}.Scd2DeltaWriter")@patch(f"{_PROCESSOR}.DeltaTableHelper")@patch(f"{_PROCESSOR}.ExternalDataJob")@patch(f"{_PROCESSOR}.s3fs")@@ -241,6 +242,7 @@ class TestProcessMessageOwnershipGate:_s3fs: MagicMock,mock_job_model: MagicMock,mock_helper_cls: MagicMock,+ mock_scd2_cls: MagicMock,_already: MagicMock,_read: MagicMock,_analytics: MagicMock,@@ -248,7 +250,6 @@ class TestProcessMessageOwnershipGate:helper = mock_helper_cls.return_valuehelper.get_delta_table = AsyncMock(return_value=None)helper.write_to_deltalake = AsyncMock()- helper.write_scd2_to_deltalake = AsyncMock()mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()def verify_ownership() -> None:@@ -258,7 +259,7 @@ class TestProcessMessageOwnershipGate:process_message(_message(), verify_ownership=verify_ownership)helper.write_to_deltalake.assert_not_called()- helper.write_scd2_to_deltalake.assert_not_called()+ mock_scd2_cls.return_value.write.assert_not_called()@patch(f"{_PROCESSOR}.posthoganalytics")@patch(f"{_PROCESSOR}._mark_job_completed")