Skip to content

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

feat(warehouse): deltalite real-write path (phase 2, flag-gated) (#75884)

Tom Owersbe94dce56926
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.py
index cae54b98ee01..88a3780f88d8 100644
--- a/posthog/settings/data_warehouse.py
+++ b/posthog/settings/data_warehouse.py
@@ -70,38 +70,6 @@ DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES: int | None = get_from_
"DATA_WAREHOUSE_DELTA_MERGE_MAX_TEMP_DIRECTORY_SIZE_BYTES", None, optional=True, type_cast=int
)
-# --- deltalite shadow verification (rollout canary, phase 1) -------------------------------------
-# When enabled, the incremental merge path ALSO re-applies the same batch through the deltalite
-# streaming upsert into a throwaway copy of the affected partitions, then compares the result to
-# the real (delta-rs MERGE) output. deltalite NEVER writes the real table — this is pure observation
-# to build confidence that deltalite is byte-for-byte equivalent before it writes production tables.
-#
-# This env var is the cheap master switch, checked first so that when it's off nothing runs at all
-# (no DB query, no feature-flag eval, no extra I/O). Per-schema canary targeting is a PostHog feature
-# flag on top of this (see deltalite_shadow.is_deltalite_shadow_enabled). Off by default.
-DATA_WAREHOUSE_DELTALITE_SHADOW_ENABLED = get_from_env(
- "DATA_WAREHOUSE_DELTALITE_SHADOW_ENABLED", False, type_cast=str_to_bool
-)
-# Fraction of eligible incremental batches to shadow. The comparison roughly doubles a batch's I/O
-# (seed copy + upsert + compare read), so sample rather than shadow every batch. 1.0 = all, 0.0 = none.
-DATA_WAREHOUSE_DELTALITE_SHADOW_SAMPLE_RATE = get_from_env(
- "DATA_WAREHOUSE_DELTALITE_SHADOW_SAMPLE_RATE", 1.0, type_cast=float
-)
-# Skip the shadow for any batch whose affected partitions exceed this at-rest (compressed) byte size —
-# seeding and re-reading them would be too expensive. Measured from the Delta add-action stats before
-# any data is read, so an oversized batch is skipped cheaply. 0 disables the cap.
-DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_BYTES = get_from_env(
- "DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_BYTES", 2_000_000_000, type_cast=int
-)
-# Also skip when the affected partitions hold more than this many rows. The byte cap above is measured
-# on the *compressed* at-rest size, which a highly compressible partition understates badly — a small
-# on-S3 slice can explode into a huge Arrow working set once the seed + comparison decompress it. Rows
-# bound that uncompressed set directly. When the row/byte estimate can't be read at all, the shadow
-# fails closed (skips) rather than materializing an unbounded slice. 0 disables the cap.
-DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_ROWS = get_from_env(
- "DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_ROWS", 20_000_000, type_cast=int
-)
-
GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL")
GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY")
GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID: str | None = os.getenv("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID")
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.py
index 4b5c460aeffb..ea8bd5a14371 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
@@ -1,5 +1,6 @@
import json
import asyncio
+import contextlib
from collections.abc import Callable, Sequence
from typing import Any, Literal
@@ -541,48 +542,95 @@ class DeltaTableHelper:
)
return deduped
- async def _maybe_run_deltalite_shadow(
+ async def _write_via_deltalite(
self,
*,
+ existing_delta_table: deltalake.DeltaTable,
data: pa.Table,
- primary_keys: list[str],
- partition_key: str | None,
- version_before: int,
- version_after: int | None,
+ normalized_primary_keys: list[str],
+ use_partitioning: bool,
commit_metadata: dict[str, str] | None,
- ) -> None:
- """Best-effort deltalite shadow verification for this incremental batch.
-
- Checks the per-schema rollout flag, then re-applies the batch through deltalite into a
- throwaway copy and compares to the merge result (see ``deltalite_shadow``). Wrapped so that
- nothing here — flag eval, import, comparison — can ever raise into the real sync. Imported
- lazily to avoid a circular import (``deltalite_shadow`` reuses ``_purge_s3_prefix``).
+ ) -> bool:
+ """Phase 2: perform the incremental merge via deltalite instead of the delta-rs MERGE.
+
+ Returns True if deltalite committed the write (caller then skips the delta-rs MERGE), or False
+ to fall back to the MERGE. Falls back on *anything* — flag off, import failure, deltalite error /
+ commit conflict / refusal — so switching a schema to deltalite can only change which engine
+ writes, never whether the sync succeeds; the worst case is today's behaviour. Controlled solely
+ by the per-schema ``data-warehouse-deltalite-write`` feature flag (no env switch), so it can be
+ ramped / killed entirely from the flag UI without a deploy.
"""
+ if not normalized_primary_keys:
+ return False
+
+ # The flag check is a rollout gate, not part of the write: a flag miss (off) or any error here
+ # (including the import) must fall back to the delta-rs MERGE *silently*.
try:
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.deltalite_shadow import (
- is_deltalite_shadow_enabled,
- run_shadow_comparison,
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.deltalite_write import (
+ is_deltalite_write_enabled,
)
- enabled = await database_sync_to_async_pool(is_deltalite_shadow_enabled)(
+ enabled = await database_sync_to_async_pool(is_deltalite_write_enabled)(
self._job.team_id, str(self._job.schema_id), None
)
- if not enabled:
- return
+ except Exception: # noqa: BLE001 - a flag-eval / import error just means "don't use deltalite"
+ return False
+ if not enabled:
+ return False
- await run_shadow_comparison(
- uri=await self._get_delta_table_uri(),
- storage_options=self._get_credentials(),
- data=data,
- primary_keys=primary_keys,
- partition_key=partition_key,
- version_before=version_before,
- version_after=version_after,
- commit_metadata=commit_metadata,
- logger=self._logger,
+ # deltalite is enabled. Only the upsert *commit* gates the fallback: a pre-commit failure means
+ # nothing was written, so we re-run the delta-rs MERGE. Anything AFTER the commit is best-effort
+ # bookkeeping and must NOT return False — otherwise the MERGE would re-run on top of deltalite's
+ # already-committed write. (Lazy metrics import keeps the heavy pipeline_v3 chain off the module
+ # import path — circular.)
+ try:
+ import deltalite
+
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
+ DELTALITE_WRITE_TOTAL,
)
- except Exception as e: # noqa: BLE001 - shadow must never affect the sync
- await self._logger.awarning(f"deltalite shadow wrapper errored (ignored): {e}")
+
+ uri = await self._get_delta_table_uri()
+ storage_options = self._get_credentials()
+ partition_key = PARTITION_KEY if use_partitioning else None
+
+ def _upsert() -> Any:
+ table = deltalite.DeltaLiteTable.open(uri, storage_options)
+ return table.upsert(
+ data,
+ list(normalized_primary_keys),
+ partition_key,
+ commit_metadata=commit_metadata,
+ )
+
+ stats = await asyncio.to_thread(_upsert)
+ except Exception as e: # noqa: BLE001 - pre-commit failure: nothing committed, fall back to MERGE
+ await self._logger.awarning(
+ f"deltalite write failed; falling back to delta-rs MERGE (sync unaffected): {e}"
+ )
+ try:
+ DELTALITE_WRITE_TOTAL.labels(outcome="fallback").inc()
+ except Exception: # noqa: BLE001 - the metrics import itself failed; the warning is enough
+ pass
+ return False
+
+ # Committed — the real table is now deltalite's output. NOTHING past this point may raise into
+ # the caller: an exception here would leave `deltalite_wrote` unset and either fail/retry the
+ # sync or re-run the delta-rs MERGE on top of deltalite's already-committed write. So every
+ # post-commit step (handle refresh, log, metric) is wrapped best-effort and we always return True.
+ try:
+ # Refresh the in-memory delta-rs handle to deltalite's new version so the table returned by
+ # write_to_deltalake (and any subsequent reads) reflects the real state.
+ await asyncio.to_thread(existing_delta_table.update_incremental)
+ await self._logger.ainfo(
+ f"deltalite write: committed v{stats.version} "
+ f"(+{stats.rows_inserted} inserted / ~{stats.rows_updated} updated / {stats.rows_copied} copied)"
+ )
+ DELTALITE_WRITE_TOTAL.labels(outcome="written").inc()
+ except Exception as e: # noqa: BLE001 - the write is committed; bookkeeping must never raise
+ with contextlib.suppress(Exception):
+ await self._logger.awarning(f"deltalite write committed but post-commit bookkeeping failed: {e}")
+ return True
async def write_to_deltalake(
self,
@@ -645,10 +693,6 @@ class DeltaTableHelper:
existing_delta_table = delta_table
- # Captured before the merge so the deltalite shadow (below) can time-travel to the exact
- # pre-merge state when it re-applies this batch into a throwaway copy.
- version_before_merge = existing_delta_table.version()
-
await self._logger.adebug(f"write_to_deltalake: merging...")
# Normalize keys and check the keys actually exist in the dataset
@@ -660,7 +704,19 @@ class DeltaTableHelper:
normalized_primary_keys.append(n)
predicate_ops = _merge_predicate_ops(normalized_primary_keys)
- if use_partitioning:
+
+ # Phase 2 canary: try deltalite for the real merge. On success the delta-rs MERGE (and the
+ # now-redundant forward shadow) below are skipped; on any failure this returns False and we
+ # fall through to the MERGE, so a deltalite issue can never fail the sync.
+ deltalite_wrote = await self._write_via_deltalite(
+ existing_delta_table=existing_delta_table,
+ data=data,
+ normalized_primary_keys=normalized_primary_keys,
+ use_partitioning=use_partitioning,
+ commit_metadata=commit_metadata,
+ )
+
+ if not deltalite_wrote and use_partitioning:
predicate_ops.append(f"source.{PARTITION_KEY} = target.{PARTITION_KEY}")
# Group the table by the partition key and merge multiple times with streamed_exec=True for optimised merging
@@ -714,7 +770,7 @@ class DeltaTableHelper:
if progress_callback:
progress_callback()
- else:
+ elif not deltalite_wrote:
# Single merge call → safe to tag directly; this is the terminal commit.
def _do_merge_unpartitioned(data: pa.Table, predicate_ops: list[str]):
return (
@@ -738,26 +794,6 @@ class DeltaTableHelper:
"write_to_deltalake: merge",
)
await self._logger.adebug(f"Delta Merge Stats: {json.dumps(merge_stats)}")
-
- # deltalite shadow verification (rollout canary, phase 1). Re-applies this exact batch
- # through the deltalite streaming upsert into a throwaway copy and compares the result to
- # the merge above. deltalite never writes the real table; the call is best-effort and can
- # never affect the sync. Master-switched off by default (cheap env check first), then
- # gated per-schema by a feature flag.
- if settings.DATA_WAREHOUSE_DELTALITE_SHADOW_ENABLED:
- # Version the merge just produced. delta-rs advances the table in place on commit; guard
- # against it not advancing (fall back to latest) so we never read the pre-merge state.
- version_after_merge: int | None = existing_delta_table.version()
- if version_after_merge is None or version_after_merge <= version_before_merge:
- version_after_merge = None
- await self._maybe_run_deltalite_shadow(
- data=data,
- primary_keys=normalized_primary_keys,
- partition_key=PARTITION_KEY if use_partitioning else None,
- version_before=version_before_merge,
- version_after=version_after_merge,
- commit_metadata=commit_metadata,
- )
elif (
write_type == "full_refresh"
or (write_type == "incremental" and delta_table is None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_shadow.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_shadow.py
deleted file mode 100644
index 185442217b65..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_shadow.py
+++ /dev/null
@@ -1,408 +0,0 @@
-"""Shadow-mode verification for the deltalite streaming upsert (rollout canary, phase 1).
-
-deltalite is a Rust library that replaces delta-rs's SQL MERGE for the incremental sync with a
-streaming partition-level upsert. Before it ever writes a production table, we want evidence that it
-produces byte-for-byte the same result as the merge on real customer data. This module provides that
-evidence with ZERO blast radius: for an eligible incremental batch, after the real merge has already
-committed the true table, it re-applies the SAME batch through deltalite into a *throwaway copy* of
-just the affected partitions and compares the two. deltalite never touches the real table.
-
-Flow (see the rollout plan):
- 1. The real delta-rs MERGE has already run → the real table is at version N+1. The caller captured
- the pre-merge version N.
- 2. Seed a throwaway Delta table at state N, scoped to the batch's affected partition values, by
- time-travelling the real table to version N and copying only those partitions.
- 3. Run ``deltalite.upsert(batch)`` into the throwaway table.
- 4. Compare the affected partitions of the real table @ N+1 (ground truth) against the throwaway
- table via a DuckDB set-difference. Rows outside the affected partitions are untouched by both the
- merge and deltalite, so comparing only the affected partition values is exact.
- 5. Emit a ``match`` / ``mismatch`` / ``skipped`` / ``unsupported`` / ``error`` metric, then delete
- the throwaway prefix.
-
-Everything here is best-effort. A shadow failure MUST NOT affect the real sync — the caller wraps the
-invocation in a broad ``try/except`` and treats any exception as an ignored shadow error. The
-``deltalite`` import is guarded so the module is inert (records nothing but an ``error`` metric) until
-the wheel is published + pinned by the ``build-deltalite`` workflow at rollout time.
-"""
-
-from __future__ import annotations
-
-import hmac
-import random
-import asyncio
-import hashlib
-from collections.abc import Sequence
-from typing import Any
-
-from django.conf import settings
-
-import duckdb
-import pyarrow as pa
-import deltalake
-import pyarrow.compute as pc
-import posthoganalytics
-from structlog.types import FilteringBoundLogger
-
-from products.data_warehouse.backend.facade.api import aget_s3_client
-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
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.metrics import (
- DELTALITE_SHADOW_DURATION_SECONDS,
- DELTALITE_SHADOW_TOTAL,
-)
-
-# `deltalake` and `duckdb` are hard dependencies (the merge path and the comparison engine),
-# imported normally. deltalite is NOT a dependency yet — the wheel is published + pinned by the
-# `build-deltalite` workflow at rollout time — so its import is guarded: this module, and therefore
-# the sync, is unaffected when the wheel isn't installed.
-try:
- import deltalite
-
- _DELTALITE_AVAILABLE = True
-except ImportError: # pragma: no cover - exercised only where the wheel isn't installed
- deltalite = None # ty: ignore[invalid-assignment]
- _DELTALITE_AVAILABLE = False
-
-
-WAREHOUSE_DELTALITE_SHADOW_FLAG = "data-warehouse-deltalite-shadow"
-
-# Suffix for the throwaway copy. Includes the run so concurrent syncs of the same table never collide,
-# and is easy to grep/lifecycle-sweep. Lives under the same bucket as the real table.
-_SHADOW_SUFFIX = "__deltalite_shadow"
-
-
-def is_deltalite_shadow_enabled(team_id: int, schema_id: str, source_type: str | None = None) -> bool:
- """Evaluate the per-schema shadow rollout flag.
-
- ``schema_id`` (and ``team_id`` / ``source_type``) are passed as person properties so the flag can
- be released to a single table first — set a release condition ``schema_id = <id>`` to shadow one
- schema before ramping by team / org / source. Mirrors ``is_auto_repartition_enabled``.
-
- Any evaluation failure returns False (fail closed): a flags-service blip must never accidentally
- switch the shadow on.
- """
- from posthog.models import Team
-
- try:
- team = Team.objects.only("uuid", "organization_id").get(id=team_id)
- except Team.DoesNotExist:
- return False
-
- # Resolve source_type from the schema when the caller didn't supply it, so a `source_type = <x>`
- # release condition can actually match (mirrors is_auto_repartition_enabled). Best-effort: a lookup
- # failure just omits the property rather than failing the whole check.
- if source_type is None:
- try:
- from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
-
- schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id)
- source_type = schema.source.source_type
- except Exception:
- source_type = None
-
- person_properties: dict[str, str] = {"schema_id": str(schema_id), "team_id": str(team_id)}
- if source_type is not None:
- person_properties["source_type"] = source_type
-
- try:
- return bool(
- posthoganalytics.feature_enabled(
- WAREHOUSE_DELTALITE_SHADOW_FLAG,
- str(team.uuid),
- groups={"organization": str(team.organization_id), "project": str(team_id)},
- person_properties=person_properties,
- group_properties={
- "organization": {"id": str(team.organization_id)},
- "project": {"id": str(team_id)},
- },
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- return False
-
-
-def _record(outcome: str) -> None:
- DELTALITE_SHADOW_TOTAL.labels(outcome=outcome).inc()
-
-
-def _pk_digest(row: Sequence[Any]) -> str:
- """Keyed, truncated digest of one primary-key tuple, safe to log.
-
- HMAC-SHA256 with the server secret so a low-entropy key (a small integer ID, an email) can't be
- recovered by brute-forcing the hash from log access; the key is stable across runs/processes so the
- same PK always maps to the same digest for cross-run correlation.
- """
- payload = "\x1f".join(map(str, row)).encode()
- return hmac.new(settings.SECRET_KEY.encode(), payload, hashlib.sha256).hexdigest()[:12]
-
-
-def _affected_partition_values(data: pa.Table, partition_key: str | None) -> list[str] | None:
- """Distinct partition values in the batch, or None when the table is unpartitioned (= whole table)."""
- if partition_key is None or partition_key not in data.column_names:
- return None
- return [v.as_py() for v in pc.unique(data[partition_key])]
-
-
-def _affected_at_rest_stats(
- uri: str, storage_options: dict[str, str], version: int, affected: list[str] | None
-) -> tuple[int, int] | None:
- """Compressed on-S3 size and row count of the affected partitions at ``version``, from Delta stats.
-
- Metadata only — no data is read. Used to skip oversized batches cheaply before anything is
- materialized. Returns ``(compressed_bytes, rows)``, or ``None`` when the stats can't be read so the
- caller can fail closed (skip) rather than materialize an unbounded slice into worker memory.
-
- ``rows`` bounds the *uncompressed* working set the way ``compressed_bytes`` can't: a highly
- compressible partition is tiny on S3 but explodes once decompressed into the Arrow comparison, so
- a small at-rest size alone doesn't prove the batch is safe to shadow.
- """
- try:
- dt = deltalake.DeltaTable(uri, version=version, storage_options=storage_options)
- # get_add_actions returns an arro3 Table; read columns via its own API and sum in Python
- # (a table has a few hundred files at most, so this is cheap and avoids arrow-compute typing).
- adds = dt.get_add_actions(flatten=True)
- if "size_bytes" not in adds.column_names or "num_records" not in adds.column_names:
- return None
- sizes = adds["size_bytes"].to_pylist()
- records = adds["num_records"].to_pylist()
- if affected is None:
- return sum(int(s or 0) for s in sizes), sum(int(r or 0) for r in records)
- part_col_name = f"partition.{PARTITION_KEY}"
- if part_col_name not in adds.column_names:
- # Partitioned read requested but the partition column is absent from the stats — we can't
- # scope the estimate, so treat it as unknown and let the caller fail closed.
- return None
- parts = adds[part_col_name].to_pylist()
- affected_set = {str(a) for a in affected}
- return (
- sum(int(s or 0) for s, p in zip(sizes, parts) if str(p) in affected_set),
- sum(int(r or 0) for r, p in zip(records, parts) if str(p) in affected_set),
- )
- except Exception:
- return None
-
-
-def _read_affected(
- uri: str, storage_options: dict[str, str], version: int | None, affected: list[str] | None
-) -> pa.Table:
- """Read the affected partitions of the table (at ``version`` if given, else latest)."""
- dt = deltalake.DeltaTable(uri, version=version, storage_options=storage_options)
- if affected is None:
- return dt.to_pyarrow_table()
- return dt.to_pyarrow_table(partitions=[(PARTITION_KEY, "in", [str(a) for a in affected])])
-
-
-def _seed_shadow(seed: pa.Table, shadow_uri: str, storage_options: dict[str, str], partition_key: str | None) -> None:
- deltalake.write_deltalake(
- shadow_uri,
- seed,
- partition_by=[partition_key] if partition_key else None,
- mode="overwrite",
- storage_options=storage_options,
- )
-
-
-def _run_deltalite_upsert(
- shadow_uri: str,
- storage_options: dict[str, str],
- data: pa.Table,
- primary_keys: Sequence[str],
- partition_key: str | None,
- commit_metadata: dict[str, str] | None,
-) -> None:
- table = deltalite.DeltaLiteTable.open(shadow_uri, storage_options)
- table.upsert(
- data,
- list(primary_keys),
- partition_key,
- commit_metadata=commit_metadata,
- )
-
-
-def _compare(real: pa.Table, shadow: pa.Table, primary_keys: Sequence[str]) -> tuple[bool, dict[str, Any]]:
- """Order-independent logical comparison of two Arrow tables.
-
- Returns ``(is_match, diagnostics)``. Diagnostics contain only row counts, column sets, and
- *hashes* of diverging primary keys — never row payloads and never raw key values — so nothing
- sensitive is logged.
- """
- real_cols = set(real.column_names)
- shadow_cols = set(shadow.column_names)
- if real_cols != shadow_cols:
- return False, {
- "reason": "schema_mismatch",
- "only_real_cols": sorted(real_cols - shadow_cols),
- "only_shadow_cols": sorted(shadow_cols - real_cols),
- }
-
- # Compare field *types*, not just names. DuckDB EXCEPT ALL implicitly casts when the two sides
- # differ, so an int32-vs-int64, timestamp-precision, or decimal-scale divergence would otherwise
- # slip through as a false match. Catch it here before the row comparison.
- type_mismatches = {
- name: [str(real.schema.field(name).type), str(shadow.schema.field(name).type)]
- for name in real.column_names
- if not real.schema.field(name).type.equals(shadow.schema.field(name).type)
- }
- if type_mismatches:
- return False, {"reason": "schema_type_mismatch", "type_mismatches": type_mismatches}
-
- # Align column order (EXCEPT ALL matches by position) to the real table's order.
- shadow = shadow.select(real.column_names)
-
- con = duckdb.connect()
- try:
- con.register("real_t", real)
- con.register("shadow_t", shadow)
- counts = con.execute(
- """
- SELECT
- (SELECT count(*) FROM real_t),
- (SELECT count(*) FROM shadow_t),
- (SELECT count(*) FROM (SELECT * FROM real_t EXCEPT ALL SELECT * FROM shadow_t)),
- (SELECT count(*) FROM (SELECT * FROM shadow_t EXCEPT ALL SELECT * FROM real_t))
- """
- ).fetchone()
- assert counts is not None # the aggregate query always returns exactly one row
- real_n, shadow_n, only_real, only_shadow = counts
-
- if only_real == 0 and only_shadow == 0 and real_n == shadow_n:
- return True, {"rows": real_n}
-
- pk_cols = ", ".join(f'"{c}"' for c in primary_keys)
- diverging = (
- con.execute(
- f"SELECT {pk_cols} FROM (SELECT * FROM real_t EXCEPT ALL SELECT * FROM shadow_t) LIMIT 20"
- ).fetchall()
- if pk_cols
- else []
- )
- return False, {
- "reason": "content_mismatch",
- "real_rows": real_n,
- "shadow_rows": shadow_n,
- "only_in_real": only_real,
- "only_in_shadow": only_shadow,
- # Keyed HMACs of the diverging rows' primary keys — never the raw values. A warehouse PK can
- # itself be sensitive (e.g. a table keyed by email or a small integer ID); a plain hash of a
- # low-entropy key is trivially reversible by anyone with log access, so the HMAC is keyed with
- # the server secret to defeat enumeration while still letting us count distinct diverging keys
- # and correlate them across runs (the key is stable server-side).
- "diverging_pk_hashes": [_pk_digest(row) for row in diverging],
- }
- finally:
- con.close()
-
-
-async def run_shadow_comparison(
- *,
- uri: str,
- storage_options: dict[str, str],
- data: pa.Table,
- primary_keys: Sequence[str],
- partition_key: str | None,
- version_before: int,
- version_after: int | None = None,
- commit_metadata: dict[str, str] | None,
- logger: FilteringBoundLogger,
-) -> None:
- """Shadow one incremental batch. Best-effort; never raises (all failures become an ``error`` metric).
-
- Args mirror the merge call site: ``data`` is the already-deduped batch, ``primary_keys`` are the
- normalized PK columns, ``partition_key`` is ``PARTITION_KEY`` when the table is partitioned else
- ``None``, ``version_before`` is the real table's version *before* the merge committed, and
- ``version_after`` is the version the merge produced. The real side is read at ``version_after`` so a
- commit landing between the merge and this read (e.g. a concurrent sync) can't cause a false
- mismatch; ``None`` falls back to latest.
- """
- if not _DELTALITE_AVAILABLE:
- _record("error")
- await logger.adebug("deltalite shadow: deltalite wheel not installed; skipping")
- return
-
- if random.random() >= settings.DATA_WAREHOUSE_DELTALITE_SHADOW_SAMPLE_RATE:
- _record("skipped")
- return
-
- if data.num_rows == 0:
- _record("skipped")
- return
-
- affected = _affected_partition_values(data, partition_key)
- shadow_uri = f"{uri.rstrip('/')}{_SHADOW_SUFFIX}_{random.getrandbits(48):012x}"
-
- try:
- with DELTALITE_SHADOW_DURATION_SECONDS.time():
- byte_cap = settings.DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_BYTES
- row_cap = settings.DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_ROWS
- if (byte_cap and byte_cap > 0) or (row_cap and row_cap > 0):
- stats = await asyncio.to_thread(_affected_at_rest_stats, uri, storage_options, version_before, affected)
- if stats is None:
- # Fail closed: without a size estimate we can't bound the working set the seed +
- # comparison will materialize, and the shadow OOMing kills every co-tenant activity
- # on the pod. A missed sample is free; an OOM is not.
- _record("skipped")
- await logger.adebug("deltalite shadow: affected-partition size unknown; skipping (fail closed)")
- return
- affected_bytes, affected_rows = stats
- if byte_cap and byte_cap > 0 and affected_bytes > byte_cap:
- _record("skipped")
- await logger.adebug(
- f"deltalite shadow: affected partitions {affected_bytes}B over cap {byte_cap}B; skipping"
- )
- return
- if row_cap and row_cap > 0 and affected_rows > row_cap:
- _record("skipped")
- await logger.adebug(
- f"deltalite shadow: affected partitions {affected_rows} rows over cap {row_cap}; skipping"
- )
- return
-
- # 1. Seed a throwaway table from the pre-merge state of the affected partitions.
- seed = await asyncio.to_thread(_read_affected, uri, storage_options, version_before, affected)
- await asyncio.to_thread(_seed_shadow, seed, shadow_uri, storage_options, partition_key)
-
- # 2. Apply the same batch through deltalite.
- try:
- await asyncio.to_thread(
- _run_deltalite_upsert,
- shadow_uri,
- storage_options,
- data,
- primary_keys,
- partition_key,
- commit_metadata,
- )
- except Exception as e: # noqa: BLE001 - classify deltalite's typed refusals
- if type(e).__name__ == "DeltaLiteUnsupportedTableError":
- _record("unsupported")
- await logger.ainfo(f"deltalite shadow: table not supported by deltalite: {e}")
- return
- raise
-
- # 3. Compare against the real (post-merge) result of the affected partitions, pinned to the
- # version the merge produced so a commit landing in between can't fake a mismatch.
- real = await asyncio.to_thread(_read_affected, uri, storage_options, version_after, affected)
- shadow_result = await asyncio.to_thread(_read_affected, shadow_uri, storage_options, None, None)
- is_match, diag = await asyncio.to_thread(_compare, real, shadow_result, primary_keys)
-
- if is_match:
- _record("match")
- await logger.adebug(f"deltalite shadow: MATCH ({diag.get('rows')} rows)")
- else:
- _record("mismatch")
- # A genuine deltalite correctness bug. Loud, but PII-safe (counts + PK hashes only).
- await logger.aerror(f"deltalite shadow: MISMATCH — {diag}")
- except Exception as e: # noqa: BLE001 - shadow must never affect the sync
- _record("error")
- await logger.awarning(f"deltalite shadow: errored (ignored, real sync unaffected): {e}")
- finally:
- # Always clean up the throwaway prefix.
- try:
- async with aget_s3_client(fresh_instance=True) as s3:
- await _purge_s3_prefix(s3, shadow_uri)
- except FileNotFoundError:
- pass
- except Exception as e: # noqa: BLE001
- await logger.awarning(f"deltalite shadow: cleanup of {shadow_uri} failed: {e}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_write.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_write.py
new file mode 100644
index 000000000000..8b73b71d578a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_write.py
@@ -0,0 +1,62 @@
+"""Per-schema feature-flag gating for the deltalite real-write path (phase 2).
+
+When the ``data-warehouse-deltalite-write`` flag matches a schema, deltalite performs the incremental
+merge (``DeltaLiteTable.upsert``) instead of the delta-rs ``MERGE`` — see
+``DeltaTableHelper._write_via_deltalite``. A deltalite failure falls back to the MERGE, so the flag
+only ever changes *which engine* writes, never whether the sync succeeds.
+"""
+
+import posthoganalytics
+
+WAREHOUSE_DELTALITE_WRITE_FLAG = "data-warehouse-deltalite-write"
+
+
+def is_deltalite_write_enabled(team_id: int, schema_id: str, source_type: str | None = None) -> bool:
+ """Evaluate the per-schema deltalite write rollout flag.
+
+ ``schema_id`` / ``team_id`` / ``source_type`` are passed as person properties so the flag can be
+ released to a single table first (release condition ``schema_id = <id>``) before ramping by team /
+ org / source. Mirrors ``is_auto_repartition_enabled``. This flag is the only control (no env
+ switch), so the write path can be ramped or killed from the flag UI without a deploy. Any
+ evaluation failure returns False (fail closed): a flags-service blip must never accidentally switch
+ it on.
+ """
+ from posthog.models import Team
+
+ try:
+ team = Team.objects.only("uuid", "organization_id").get(id=team_id)
+ except Team.DoesNotExist:
+ return False
+
+ # Resolve source_type from the schema when the caller didn't supply it, so a `source_type = <x>`
+ # release condition can actually match. Best-effort: a lookup failure just omits the property.
+ if source_type is None:
+ try:
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+ schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id)
+ source_type = schema.source.source_type
+ except Exception:
+ source_type = None
+
+ person_properties: dict[str, str] = {"schema_id": str(schema_id), "team_id": str(team_id)}
+ if source_type is not None:
+ person_properties["source_type"] = source_type
+
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ WAREHOUSE_DELTALITE_WRITE_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team_id)},
+ person_properties=person_properties,
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team_id)},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ return False
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.py
index e16e16e291aa..c456a396dc7b 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
@@ -1371,3 +1371,134 @@ class TestNullSafeMergePredicate:
# Documents the pre-fix behaviour the null-safe predicate corrects.
result = self._seed_then_merge(tmp_path / "unsafe", ["source.id = target.id", "source.seg = target.seg"])
assert result.num_rows == 2
+
+
+class TestDeltaliteWritePath:
+ """Phase 2: deltalite performs the real incremental merge, gated solely by a per-schema flag, with
+ a hard fallback to the delta-rs MERGE so a deltalite failure can never fail a sync."""
+
+ _FLAG = (
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core."
+ "deltalite_write.is_deltalite_write_enabled"
+ )
+
+ @pytest.fixture(autouse=True)
+ def _preload_write_metrics(self):
+ # _write_via_deltalite lazily imports the pipeline_v3 metrics module. These tests fake the
+ # `deltalite` module via patch.dict(sys.modules, ...), which on exit restores the enter-time
+ # snapshot and thus evicts any module first imported *inside* the block. If the metrics module
+ # were first loaded there, the next test would re-execute it and hit "Duplicated timeseries" in
+ # the global Prometheus registry. Loading it here (at setup, before any patch.dict) keeps it in
+ # the snapshot so it survives. Imported at runtime — not module top — to keep the heavy
+ # pipeline_v3 chain off collection.
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load import ( # noqa: F401
+ metrics,
+ )
+
+ def _helper(self) -> DeltaTableHelper:
+ return DeltaTableHelper(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=_make_logger())
+
+ async def _call(self, helper: DeltaTableHelper) -> bool:
+ return await helper._write_via_deltalite(
+ existing_delta_table=MagicMock(),
+ data=pa.table({"id": pa.array([1], pa.int64())}),
+ normalized_primary_keys=["id"],
+ use_partitioning=False,
+ commit_metadata={"run_uuid": "abc"},
+ )
+
+ @pytest.mark.asyncio
+ async def test_skips_without_primary_keys(self):
+ # No primary keys => nothing to key an upsert on; fall back without even evaluating the flag.
+ with patch(self._FLAG) as flag:
+ wrote = await self._helper()._write_via_deltalite(
+ existing_delta_table=MagicMock(),
+ data=pa.table({"id": pa.array([1], pa.int64())}),
+ normalized_primary_keys=[],
+ use_partitioning=False,
+ commit_metadata=None,
+ )
+ assert wrote is False
+ flag.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_falls_back_when_flag_disabled(self):
+ with patch(self._FLAG, return_value=False):
+ assert await self._call(self._helper()) is False
+
+ @pytest.mark.asyncio
+ async def test_writes_via_deltalite_when_enabled(self):
+ helper = self._helper()
+ existing = MagicMock()
+ fake_stats = MagicMock(version=5, rows_inserted=3, rows_updated=2, rows_copied=10)
+ fake_table = MagicMock()
+ fake_table.upsert.return_value = fake_stats
+ fake_deltalite = MagicMock()
+ fake_deltalite.DeltaLiteTable.open.return_value = fake_table
+ with (
+ patch(self._FLAG, return_value=True),
+ patch.dict("sys.modules", {"deltalite": fake_deltalite}),
+ patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value="s3://b/t")),
+ patch.object(helper, "_get_credentials", return_value={"AWS_REGION": "us-east-1"}),
+ ):
+ wrote = await helper._write_via_deltalite(
+ existing_delta_table=existing,
+ data=pa.table({"id": pa.array([1], pa.int64())}),
+ normalized_primary_keys=["id"],
+ use_partitioning=True,
+ commit_metadata={"run_uuid": "abc"},
+ )
+ assert wrote is True
+ fake_deltalite.DeltaLiteTable.open.assert_called_once_with("s3://b/t", {"AWS_REGION": "us-east-1"})
+ fake_table.upsert.assert_called_once()
+ # PARTITION_KEY is passed as the partition arg when the table is partitioned.
+ assert fake_table.upsert.call_args.args[2] == PARTITION_KEY
+ existing.update_incremental.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_falls_back_when_deltalite_raises(self):
+ helper = self._helper()
+ fake_table = MagicMock()
+ fake_table.upsert.side_effect = RuntimeError("commit conflict, retries exhausted")
+ fake_deltalite = MagicMock()
+ fake_deltalite.DeltaLiteTable.open.return_value = fake_table
+ with (
+ patch(self._FLAG, return_value=True),
+ patch.dict("sys.modules", {"deltalite": fake_deltalite}),
+ patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value="s3://b/t")),
+ patch.object(helper, "_get_credentials", return_value={}),
+ ):
+ wrote = await self._call(helper)
+ assert wrote is False # deltalite blew up -> caller falls through to the delta-rs MERGE
+
+ @parameterized.expand([("refresh",), ("log",)])
+ @pytest.mark.asyncio
+ async def test_post_commit_failure_does_not_fall_back(self, failing_step: str):
+ # Once the upsert commits, NO post-commit step (handle refresh, log, metric) may raise into the
+ # caller — that would return False / bubble up and re-run the MERGE on top of deltalite's commit.
+ logger = _make_logger() # set the side effect on the mock before it becomes the typed _logger attr
+ existing = MagicMock()
+ if failing_step == "refresh":
+ existing.update_incremental.side_effect = RuntimeError("post-commit refresh boom")
+ else:
+ logger.ainfo.side_effect = RuntimeError("post-commit log boom")
+ helper = DeltaTableHelper(resource_name="t", job=MagicMock(team_id=2, schema_id="sch-1"), logger=logger)
+ fake_table = MagicMock()
+ fake_table.upsert.return_value = MagicMock(version=5, rows_inserted=1, rows_updated=0, rows_copied=0)
+ fake_deltalite = MagicMock()
+ fake_deltalite.DeltaLiteTable.open.return_value = fake_table
+ with (
+ patch(self._FLAG, return_value=True),
+ patch.dict("sys.modules", {"deltalite": fake_deltalite}),
+ patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value="s3://b/t")),
+ patch.object(helper, "_get_credentials", return_value={}),
+ ):
+ wrote = await helper._write_via_deltalite(
+ existing_delta_table=existing,
+ data=pa.table({"id": pa.array([1], pa.int64())}),
+ normalized_primary_keys=["id"],
+ use_partitioning=False,
+ commit_metadata=None,
+ )
+ assert wrote is True # committed; the post-commit failure is swallowed
+ fake_table.upsert.assert_called_once()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_shadow.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_shadow.py
deleted file mode 100644
index a889d36c7390..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_shadow.py
+++ /dev/null
@@ -1,273 +0,0 @@
-"""Unit tests for the deltalite shadow verification.
-
-These cover the parts that don't need the `deltalite` wheel installed (it isn't a dependency yet):
-the comparison engine, the affected-partition derivation, the flag gating, and — most importantly —
-the invariant that the shadow can NEVER raise into the real sync. The full seed→upsert→compare path
-against real deltalite output is covered by the deltalite crate's own differential parity suite and
-is validated live in the rollout canary.
-"""
-
-from typing import Any
-
-import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
-
-from django.test import override_settings
-
-import pyarrow as pa
-
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import deltalite_shadow
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
-
-
-def _table(ids: list[str], values: list[int], parts: list[str] | None = None) -> pa.Table:
- cols: dict[str, Any] = {
- "id": pa.array(ids, pa.string()),
- "v": pa.array(values, pa.int64()),
- }
- if parts is not None:
- cols[PARTITION_KEY] = pa.array(parts, pa.string())
- return pa.table(cols)
-
-
-# --------------------------------------------------------------------------------------
-# _compare — the comparison engine (duckdb; no deltalite needed)
-# --------------------------------------------------------------------------------------
-
-
-def test_compare_identical_tables_match():
- real = _table(["a", "b", "c"], [1, 2, 3])
- shadow = _table(["c", "a", "b"], [3, 1, 2]) # same content, different row order
- is_match, diag = deltalite_shadow._compare(real, shadow, ["id"])
- assert is_match
- assert diag["rows"] == 3
-
-
-def test_compare_content_mismatch_is_detected_with_pk_diagnostics():
- real = _table(["a", "b", "c"], [1, 2, 3])
- shadow = _table(["a", "b", "c"], [1, 2, 999]) # c differs
- is_match, diag = deltalite_shadow._compare(real, shadow, ["id"])
- assert not is_match
- assert diag["reason"] == "content_mismatch"
- assert diag["only_in_real"] == 1 and diag["only_in_shadow"] == 1
- # A keyed digest of the diverging PK is reported (one diverging row), never the raw value or payload.
- assert diag["diverging_pk_hashes"] == [deltalite_shadow._pk_digest(["c"])]
- assert "c" not in diag["diverging_pk_hashes"]
-
-
-def test_compare_row_count_mismatch_is_detected():
- real = _table(["a", "b", "c"], [1, 2, 3])
- shadow = _table(["a", "b"], [1, 2])
- is_match, diag = deltalite_shadow._compare(real, shadow, ["id"])
- assert not is_match
- assert diag["real_rows"] == 3 and diag["shadow_rows"] == 2
-
-
-def test_compare_schema_mismatch_is_detected_before_reading_rows():
- real = _table(["a"], [1])
- shadow = pa.table({"id": pa.array(["a"], pa.string()), "OTHER": pa.array([1], pa.int64())})
- is_match, diag = deltalite_shadow._compare(real, shadow, ["id"])
- assert not is_match
- assert diag["reason"] == "schema_mismatch"
- assert diag["only_real_cols"] == ["v"] and diag["only_shadow_cols"] == ["OTHER"]
-
-
-def test_compare_column_order_does_not_cause_false_mismatch():
- real = pa.table({"id": pa.array(["a"]), "v": pa.array([1], pa.int64())})
- shadow = pa.table({"v": pa.array([1], pa.int64()), "id": pa.array(["a"])}) # reordered columns
- is_match, _ = deltalite_shadow._compare(real, shadow, ["id"])
- assert is_match
-
-
-def test_compare_type_mismatch_is_detected_even_when_values_cast_equal():
- # Same column names and equal-looking values, but v is int32 vs int64. DuckDB EXCEPT ALL would
- # implicitly cast and report a match; the explicit type check must catch the divergence.
- real = pa.table({"id": pa.array(["a"], pa.string()), "v": pa.array([1], pa.int64())})
- shadow = pa.table({"id": pa.array(["a"], pa.string()), "v": pa.array([1], pa.int32())})
- is_match, diag = deltalite_shadow._compare(real, shadow, ["id"])
- assert not is_match
- assert diag["reason"] == "schema_type_mismatch"
- assert diag["type_mismatches"]["v"] == ["int64", "int32"]
-
-
-# --------------------------------------------------------------------------------------
-# _affected_partition_values
-# --------------------------------------------------------------------------------------
-
-
-def test_affected_partitions_partitioned():
- data = _table(["a", "b", "c"], [1, 2, 3], parts=["2026-07-01", "2026-07-01", "2026-07-02"])
- result = deltalite_shadow._affected_partition_values(data, PARTITION_KEY)
- assert result is not None
- assert sorted(result) == ["2026-07-01", "2026-07-02"]
-
-
-def test_affected_partitions_unpartitioned_is_none():
- data = _table(["a", "b"], [1, 2])
- assert deltalite_shadow._affected_partition_values(data, None) is None
-
-
-# --------------------------------------------------------------------------------------
-# run_shadow_comparison — gating and the never-raises invariant
-# --------------------------------------------------------------------------------------
-
-
-def _kwargs(**over):
- base = {
- "uri": "s3://data-warehouse/team_1_stripe_abc/charges",
- "storage_options": {},
- "data": _table(["a"], [1], parts=["2026-07-01"]),
- "primary_keys": ["id"],
- "partition_key": PARTITION_KEY,
- "version_before": 3,
- "commit_metadata": None,
- "logger": AsyncMock(),
- }
- base.update(over)
- return base
-
-
-async def test_records_error_and_returns_when_deltalite_unavailable():
- metric = MagicMock()
- with (
- patch.object(deltalite_shadow, "_DELTALITE_AVAILABLE", False),
- patch.object(deltalite_shadow, "DELTALITE_SHADOW_TOTAL", metric),
- ):
- await deltalite_shadow.run_shadow_comparison(**_kwargs())
- metric.labels.assert_called_once_with(outcome="error")
-
-
-async def test_sampled_out_records_skipped_and_does_no_work():
- metric = MagicMock()
- with (
- override_settings(DATA_WAREHOUSE_DELTALITE_SHADOW_SAMPLE_RATE=0.0),
- patch.object(deltalite_shadow, "_DELTALITE_AVAILABLE", True),
- patch.object(deltalite_shadow, "DELTALITE_SHADOW_TOTAL", metric),
- patch.object(deltalite_shadow, "_read_affected") as read,
- ):
- await deltalite_shadow.run_shadow_comparison(**_kwargs())
- metric.labels.assert_called_once_with(outcome="skipped")
- read.assert_not_called()
-
-
-async def test_empty_batch_is_skipped():
- metric = MagicMock()
- empty = _table([], [], parts=[])
- with (
- patch.object(deltalite_shadow, "_DELTALITE_AVAILABLE", True),
- patch.object(deltalite_shadow, "DELTALITE_SHADOW_TOTAL", metric),
- ):
- await deltalite_shadow.run_shadow_comparison(**_kwargs(data=empty))
- metric.labels.assert_called_once_with(outcome="skipped")
-
-
-async def test_never_raises_and_cleans_up_on_internal_error():
- """If any step throws, the shadow records an error, swallows it, and still purges the copy."""
- metric = MagicMock()
- purge = AsyncMock()
-
- class _FakeS3:
- async def __aenter__(self):
- return MagicMock()
-
- async def __aexit__(self, *a):
- return False
-
- with (
- override_settings(
- DATA_WAREHOUSE_DELTALITE_SHADOW_SAMPLE_RATE=1.0,
- DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_BYTES=0,
- DATA_WAREHOUSE_DELTALITE_SHADOW_MAX_AFFECTED_ROWS=0,
- ),
- patch.object(deltalite_shadow, "_DELTALITE_AVAILABLE", True),
- patch.object(deltalite_shadow, "DELTALITE_SHADOW_TOTAL", metric),
- patch.object(deltalite_shadow, "_read_affected", side_effect=RuntimeError("boom")),
- patch.object(deltalite_shadow, "aget_s3_client", return_value=_FakeS3()),
- patch.object(deltalite_shadow, "_purge_s3_prefix", purge),
- ):
- # Must not raise.
- await deltalite_shadow.run_shadow_comparison(**_kwargs())
-
- metric.labels.assert_called_once_with(outcome="error")
- purge.assert_awaited_once() # cleanup happened despite the error
-
-
- "stats",
- [
- pytest.param(None, id="size_estimate_unavailable_fails_closed"),
- pytest.param((1, 20_000_001), id="row_count_over_cap"),
- ],
-)
-async def test_shadow_skips_oversized_or_unknown_batch_before_materializing(stats):
- # Unknown estimate must fail closed and an over-cap row count must skip — either way the shadow
- # never materializes the slice into worker memory, so _read_affected is not reached.
- metric = MagicMock()
- with (
- patch.object(deltalite_shadow, "_DELTALITE_AVAILABLE", True),
- patch.object(deltalite_shadow, "DELTALITE_SHADOW_TOTAL", metric),
- patch.object(deltalite_shadow, "_affected_at_rest_stats", return_value=stats),
- patch.object(deltalite_shadow, "_read_affected") as read,
- ):
- await deltalite_shadow.run_shadow_comparison(**_kwargs())
- metric.labels.assert_called_once_with(outcome="skipped")
- read.assert_not_called()
-
-
-# --------------------------------------------------------------------------------------
-# is_deltalite_shadow_enabled — fail-closed
-# --------------------------------------------------------------------------------------
-
-
-def test_flag_returns_false_when_team_missing():
- with patch("posthog.models.Team") as team_cls:
- team_cls.DoesNotExist = Exception
- team_cls.objects.only.return_value.get.side_effect = team_cls.DoesNotExist
- assert deltalite_shadow.is_deltalite_shadow_enabled(1, "abc") is False
-
-
-def test_flag_returns_false_when_evaluation_raises():
- fake_team = MagicMock(uuid="u", organization_id="o")
- with (
- patch("posthog.models.Team") as team_cls,
- patch.object(deltalite_shadow.posthoganalytics, "feature_enabled", side_effect=RuntimeError("flags down")),
- ):
- team_cls.objects.only.return_value.get.return_value = fake_team
- assert deltalite_shadow.is_deltalite_shadow_enabled(1, "abc") is False
-
-
-def test_flag_passes_schema_id_as_person_property():
- fake_team = MagicMock(uuid="u", organization_id="o")
- with (
- patch("posthog.models.Team") as team_cls,
- patch.object(deltalite_shadow.posthoganalytics, "feature_enabled", return_value=True) as fe,
- ):
- team_cls.objects.only.return_value.get.return_value = fake_team
- assert deltalite_shadow.is_deltalite_shadow_enabled(1, "sch-123", "stripe") is True
- _, kwargs = fe.call_args
- assert kwargs["person_properties"]["schema_id"] == "sch-123"
- assert kwargs["person_properties"]["source_type"] == "stripe"
- assert kwargs["send_feature_flag_events"] is False
-
-
-def test_flag_resolves_source_type_from_schema_when_not_passed():
- # When the caller omits source_type it must be resolved from the schema, otherwise a
- # `source_type = <x>` release condition can never match (the bug: it was hardcoded to None).
- fake_team = MagicMock(uuid="u", organization_id="o")
- fake_schema = MagicMock()
- fake_schema.source.source_type = "postgres"
- with (
- patch("posthog.models.Team") as team_cls,
- patch("products.warehouse_sources.backend.models.external_data_schema.ExternalDataSchema") as schema_cls,
- patch.object(deltalite_shadow.posthoganalytics, "feature_enabled", return_value=True) as fe,
- ):
- team_cls.objects.only.return_value.get.return_value = fake_team
- schema_cls.objects.select_related.return_value.get.return_value = fake_schema
- assert deltalite_shadow.is_deltalite_shadow_enabled(1, "sch-9") is True
- _, kwargs = fe.call_args
- assert kwargs["person_properties"]["source_type"] == "postgres"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_write.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_write.py
new file mode 100644
index 000000000000..d422baf8933b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_write.py
@@ -0,0 +1,57 @@
+"""Unit tests for the deltalite write-path rollout flag (is_deltalite_write_enabled).
+
+The flag is the sole control for phase 2 (deltalite performing the real incremental merge); it must
+fail closed and pass the schema/team/source_type person properties so it can be targeted per schema.
+"""
+
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import deltalite_write
+
+
+def test_flag_returns_false_when_team_missing():
+ with patch("posthog.models.Team") as team_cls:
+ team_cls.DoesNotExist = Exception
+ team_cls.objects.only.return_value.get.side_effect = team_cls.DoesNotExist
+ assert deltalite_write.is_deltalite_write_enabled(1, "abc") is False
+
+
+def test_flag_returns_false_when_evaluation_raises():
+ fake_team = MagicMock(uuid="u", organization_id="o")
+ with (
+ patch("posthog.models.Team") as team_cls,
+ patch.object(deltalite_write.posthoganalytics, "feature_enabled", side_effect=RuntimeError("flags down")),
+ ):
+ team_cls.objects.only.return_value.get.return_value = fake_team
+ assert deltalite_write.is_deltalite_write_enabled(1, "abc") is False
+
+
+def test_flag_passes_write_key_and_person_properties():
+ fake_team = MagicMock(uuid="u", organization_id="o")
+ with (
+ patch("posthog.models.Team") as team_cls,
+ patch.object(deltalite_write.posthoganalytics, "feature_enabled", return_value=True) as fe,
+ ):
+ team_cls.objects.only.return_value.get.return_value = fake_team
+ assert deltalite_write.is_deltalite_write_enabled(2, "sch-123", "stripe") is True
+ args, kwargs = fe.call_args
+ assert args[0] == deltalite_write.WAREHOUSE_DELTALITE_WRITE_FLAG == "data-warehouse-deltalite-write"
+ assert kwargs["person_properties"] == {"schema_id": "sch-123", "team_id": "2", "source_type": "stripe"}
+ assert kwargs["send_feature_flag_events"] is False
+
+
+def test_flag_resolves_source_type_from_schema_when_not_passed():
+ # When the caller omits source_type it must be resolved from the schema, so a `source_type = <x>`
+ # release condition (e.g. excluding Sentry) can actually match.
+ fake_team = MagicMock(uuid="u", organization_id="o")
+ fake_schema = MagicMock()
+ fake_schema.source.source_type = "postgres"
+ with (
+ patch("posthog.models.Team") as team_cls,
+ patch("products.warehouse_sources.backend.models.external_data_schema.ExternalDataSchema") as schema_cls,
+ patch.object(deltalite_write.posthoganalytics, "feature_enabled", return_value=True) as fe,
+ ):
+ team_cls.objects.only.return_value.get.return_value = fake_team
+ schema_cls.objects.select_related.return_value.get.return_value = fake_schema
+ assert deltalite_write.is_deltalite_write_enabled(1, "sch-9") is True
+ assert fe.call_args.kwargs["person_properties"]["source_type"] == "postgres"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
index 90252361136f..af0701cc5b29 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
@@ -47,19 +47,11 @@ DELTA_REPARTITION_SKIP_TOTAL = Counter(
labelnames=["team_id", "reason"],
)
-# deltalite shadow verification (rollout canary). `outcome` is one of:
-# match - deltalite produced byte-identical logical content to the delta-rs MERGE
-# mismatch - deltalite disagreed with MERGE (a correctness bug; investigate before rollout)
-# skipped - not run (sampled out, over the affected-bytes cap, SCD2, or no affected partitions)
-# unsupported- deltalite refused the table (deletion vectors / column mapping)
-# error - the shadow itself failed (never affects the real sync)
-DELTALITE_SHADOW_TOTAL = Counter(
- "warehouse_load_deltalite_shadow_total",
- "deltalite shadow verifications against the delta-rs MERGE, by outcome",
+# deltalite real-write path (phase 2). `outcome` is one of:
+# written - deltalite performed the incremental merge and committed
+# fallback - deltalite was enabled but failed (or refused), so the delta-rs MERGE ran instead
+DELTALITE_WRITE_TOTAL = Counter(
+ "warehouse_load_deltalite_write_total",
+ "Incremental merges routed to deltalite's real write path, by outcome",
labelnames=["outcome"],
)
-
-DELTALITE_SHADOW_DURATION_SECONDS = Histogram(
- "warehouse_load_deltalite_shadow_duration_seconds",
- "Wall-clock time of a deltalite shadow verification (seed + upsert + compare)",
-)