Skip to content

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

feat(data-warehouse): deltalite shadow verification and publish workflow (#74242)

Tom Owers9caf4aa35b4e
diff --git a/.github/workflows/build-deltalite.yml b/.github/workflows/build-deltalite.yml
new file mode 100644
index 000000000000..6ea24a8f989a
--- /dev/null
+++ b/.github/workflows/build-deltalite.yml
@@ -0,0 +1,293 @@
+name: Release deltalite
+
+# Publishes the `deltalite` Python wheel (the streaming Delta upsert, built from
+# rust/deltalite/python via maturin) to PyPI, then auto-pins the new version in
+# pyproject.toml + uv.lock so the app image installs it via `uv sync`. Mirrors
+# build-hogql-parser-rs.yml exactly.
+#
+# ONE-TIME INFRA REQUIRED BEFORE THIS CAN PUBLISH (platform/infra team):
+# 1. Create the `deltalite` project on PyPI.
+# 2. Configure PyPI trusted publishing for it against this repo + workflow, and
+# create a matching GitHub environment named `pypi-deltalite` (see the
+# `pypi-hogql-parser-rs` environment for the template).
+# Until that exists the build/version-check jobs still run (and correctly report
+# "release needed"), but the publish job cannot upload. Nothing in the app imports
+# `deltalite` until the pin lands, so this is inert until then.
+
+on:
+ pull_request:
+ paths:
+ - rust/deltalite/python/**
+ - .github/workflows/build-deltalite.yml
+
+permissions:
+ contents: read
+ pull-requests: write
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ check-version:
+ name: Check version legitimacy
+ runs-on: ubuntu-22.04
+ timeout-minutes: 5
+ outputs:
+ deltalite-release-needed: ${{ steps.version.outputs.deltalite-release-needed }}
+ local-version: ${{ steps.version.outputs.local-version }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
+ with:
+ fetch-depth: 0
+ filter: blob:none
+
+ - name: Check if rust/deltalite/python/ or the workflow has changed
+ id: changed-files
+ uses: step-security/changed-files@2e07db73e5ccdb319b9a6c7766bd46d39d304bad # v47.0.5
+ with:
+ files_yaml: |
+ deltalite:
+ - rust/deltalite/python/**
+ workflow:
+ - .github/workflows/build-deltalite.yml
+
+ - name: Check if version was bumped
+ shell: bash
+ id: version
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ DELTALITE_CHANGED: ${{ steps.changed-files.outputs.deltalite_any_changed }}
+ WORKFLOW_CHANGED: ${{ steps.changed-files.outputs.workflow_any_changed }}
+ IS_FORK: ${{ github.event.pull_request.head.repo.full_name != 'PostHog/posthog' }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ run: |
+ deltalite_release_needed='false'
+ # Local version from pyproject.toml — single source of truth, matches Cargo.toml.
+ local=$(grep -m1 '^version = ' rust/deltalite/python/pyproject.toml | sed -E 's/version = "(.*)"/\1/')
+ echo "local-version=$local" >> $GITHUB_OUTPUT
+ if [[ "$DELTALITE_CHANGED" == 'true' ]]; then
+ # 200 = version already on PyPI, 404 = needs release.
+ http_code=$(curl -o /dev/null -sSL -w '%{http_code}' "https://pypi.org/pypi/deltalite/$local/json")
+ if [[ "$http_code" == '404' ]]; then
+ deltalite_release_needed='true'
+ # Version was bumped — mark any reminder from an earlier push resolved.
+ if [ -f .github/scripts/post-reminder-section.mjs ]; then
+ GITHUB_TOKEN="$GH_TOKEN" node .github/scripts/post-reminder-section.mjs deltalite --clear "version bumped to $local"
+ fi
+ elif [[ "$http_code" == '200' ]]; then
+ message_body="It looks like the code of \`deltalite\` changed in this PR, but its version stayed the same at $local. 👀"
+ message_body+=$'\n'"Bump the version in \`rust/deltalite/python/Cargo.toml\` AND \`rust/deltalite/python/pyproject.toml\` (the two must match) before merging."
+ if [[ "$IS_FORK" == 'true' ]]; then
+ message_body+=$'\n'"This needs to be performed on a branch created on the PostHog/posthog repo itself. A PostHog team member can assist with this."
+ fi
+ if [ -f .github/scripts/post-reminder-section.mjs ]; then
+ BODY="$message_body" GITHUB_TOKEN="$GH_TOKEN" node .github/scripts/post-reminder-section.mjs deltalite warn "version bump needed"
+ else
+ echo "Skipping deltalite section — script not present on this checkout"
+ fi
+ else
+ echo "::warning::Unexpected HTTP $http_code from PyPI for deltalite $local; assuming not yet published."
+ deltalite_release_needed='true'
+ fi
+ fi
+ # Exercise the release pipeline on workflow-only edits; skip-existing makes publish a no-op.
+ if [[ "$WORKFLOW_CHANGED" == 'true' ]]; then
+ deltalite_release_needed='true'
+ fi
+ echo "deltalite-release-needed=$deltalite_release_needed" >> $GITHUB_OUTPUT
+
+ - name: Sanity check Cargo.toml and pyproject.toml versions match
+ shell: bash
+ run: |
+ pyproject_v=$(grep -m1 '^version = ' rust/deltalite/python/pyproject.toml | sed -E 's/version = "(.*)"/\1/')
+ cargo_v=$(grep -m1 '^version = ' rust/deltalite/python/Cargo.toml | sed -E 's/version = "(.*)"/\1/')
+ if [[ "$pyproject_v" != "$cargo_v" ]]; then
+ echo "::error::pyproject.toml version ($pyproject_v) does not match Cargo.toml version ($cargo_v) — they must match."
+ exit 1
+ fi
+
+ build-wheels:
+ name: Build wheels on ${{ matrix.os }} (${{ matrix.target }})
+ needs: check-version
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 30
+ if: needs.check-version.outputs.deltalite-release-needed == 'true' &&
+ github.event.pull_request.head.repo.full_name == 'PostHog/posthog'
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: ubuntu-22.04
+ target: x86_64
+ manylinux: 2_28
+ - os: ubuntu-22.04-arm
+ target: aarch64
+ manylinux: 2_28
+ # musllinux: alpine docker users (e.g. distroless setups).
+ - os: ubuntu-22.04
+ target: x86_64
+ manylinux: musllinux_1_2
+ - os: ubuntu-22.04-arm
+ target: aarch64
+ manylinux: musllinux_1_2
+ - os: macos-14
+ target: aarch64
+ - os: macos-15-intel
+ target: x86_64
+
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
+
+ - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version: '3.12.10' # 3.12.11/.12 binaries lag on macOS
+
+ - name: Build wheel via maturin
+ uses: PyO3/maturin-action@aef21716ff3dcae8a1c301d23ec3e4446972a6e3 # v1.49.3
+ with:
+ command: build
+ target: ${{ matrix.target }}
+ manylinux: ${{ matrix.manylinux || 'auto' }}
+ args: --release --out dist --manifest-path rust/deltalite/python/Cargo.toml
+ env:
+ # Override `rust/.cargo/config.toml`'s `-fuse-ld=lld` (a flox-dev
+ # optimization that assumes lld is on PATH — GitHub Actions runners
+ # don't ship it). Empty RUSTFLAGS overrides the file-level config
+ # per Cargo's precedence rules; the workspace's `tokio_unstable`
+ # cfg isn't reachable from this crate's dep graph.
+ RUSTFLAGS: ''
+
+ - name: Build sdist (linux x86_64 manylinux only)
+ if: matrix.os == 'ubuntu-22.04' && matrix.target == 'x86_64' && matrix.manylinux == '2_28'
+ uses: PyO3/maturin-action@aef21716ff3dcae8a1c301d23ec3e4446972a6e3 # v1.49.3
+ with:
+ command: sdist
+ args: --out dist --manifest-path rust/deltalite/python/Cargo.toml
+ env:
+ RUSTFLAGS: ''
+
+ - name: Upload artifact
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ # `manylinux` is included to disambiguate the two linux runs per
+ # arch (glibc 2_28 vs musllinux_1_2); macOS rows leave it unset.
+ name: wheels-${{ matrix.os }}-${{ matrix.target }}-${{ matrix.manylinux || 'native' }}
+ path: dist/*
+ if-no-files-found: error
+
+ publish:
+ name: Publish on PyPI
+ needs: [check-version, build-wheels]
+ environment: pypi-deltalite
+ permissions:
+ id-token: write # PyPI trusted publishing + provenance OIDC handshake
+ attestations: write # actions/attest-build-provenance writes here
+ runs-on: ubuntu-22.04
+ timeout-minutes: 10
+ steps:
+ - name: Download all wheel artifacts
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
+ with:
+ pattern: wheels-*
+ merge-multiple: true
+ path: dist
+
+ - name: Generate artifact attestations
+ uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2.4.0
+ with:
+ subject-path: 'dist/*'
+
+ - name: Publish package to PyPI
+ uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0
+ with:
+ # Attaches the attestations generated above to the PyPI release.
+ attestations: true
+ skip-existing: true
+
+ - name: Get app token
+ id: app-token
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
+ private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
+
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
+ with:
+ ref: ${{ github.event.pull_request.head.ref }}
+ token: ${{ steps.app-token.outputs.token }}
+
+ - name: Set up Python
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version: 3.13.13
+
+ - name: Install uv
+ id: setup-uv
+ uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
+ with:
+ version: '0.11.28'
+ enable-cache: true
+ cache-dependency-glob: uv.lock
+ save-cache: ${{ github.ref == 'refs/heads/master' }}
+
+ - name: Update deltalite in requirements
+ shell: bash
+ env:
+ RETRIES: 20
+ VERSION: ${{ needs.check-version.outputs.local-version }}
+ run: |
+ # `--refresh-package` bypasses the restored uv index cache, which
+ # otherwise won't have the version we just published. Retry anyway
+ # in case PyPI propagation lags the publish step.
+ for i in $(seq 1 "$RETRIES"); do
+ if uv add --refresh-package deltalite "deltalite==$VERSION"; then
+ break
+ fi
+ if [[ $i -eq $RETRIES ]]; then
+ echo "Failed to update deltalite in requirements"
+ exit 1
+ fi
+ sleep 0.5
+ done
+
+ - name: Check for pin changes
+ id: check-pin
+ shell: bash
+ run: |
+ if git diff --quiet pyproject.toml uv.lock; then
+ echo "changed=false" >> $GITHUB_OUTPUT
+ else
+ echo "changed=true" >> $GITHUB_OUTPUT
+ fi
+
+ - name: Commit pin
+ if: steps.check-pin.outputs.changed == 'true'
+ uses: planetscale/ghcommit-action@25309d8005ac7c3bcd61d3fe19b69e0fe47dbdde # v0.2.20
+ with:
+ commit_message: 'Use new deltalite version'
+ repo: ${{ github.repository }}
+ branch: ${{ github.event.pull_request.head.ref }}
+ file_pattern: 'pyproject.toml uv.lock'
+ env:
+ GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
+
+ - name: Verify pin is consistent with the published version
+ shell: bash
+ env:
+ CHANGED: ${{ steps.check-pin.outputs.changed }}
+ VERSION: ${{ needs.check-version.outputs.local-version }}
+ run: |
+ # The commit step is a no-op when pyproject.toml + uv.lock were already
+ # pre-bumped on the branch to the version we just published — fine.
+ # Verify the pin is consistent with the published version (i.e. the
+ # branch is in a deployable state) before declaring success.
+ if [[ "$CHANGED" != "true" ]]; then
+ pinned=$(grep -m1 'deltalite==' pyproject.toml | sed -E 's/.*deltalite==([^"]*).*/\1/')
+ if [[ "$pinned" != "$VERSION" ]]; then
+ echo "::error::deltalite published to PyPI as $VERSION but pyproject.toml pin says $pinned."
+ echo "Check the 'Update deltalite in requirements' step above for why uv add did not produce a diff."
+ exit 1
+ fi
+ echo "pyproject.toml already pinned to $VERSION; commit-pin no-op is expected."
+ fi
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.py
index 88a3780f88d8..cae54b98ee01 100644
--- a/posthog/settings/data_warehouse.py
+++ b/posthog/settings/data_warehouse.py
@@ -70,6 +70,38 @@ 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 af7ac69f09b7..ea946a7d16e4 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
@@ -468,6 +468,49 @@ class DeltaTableHelper:
)
return deduped
+ async def _maybe_run_deltalite_shadow(
+ self,
+ *,
+ data: pa.Table,
+ primary_keys: list[str],
+ partition_key: str | None,
+ version_before: int,
+ version_after: int | None,
+ 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``).
+ """
+ try:
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.deltalite_shadow import (
+ is_deltalite_shadow_enabled,
+ run_shadow_comparison,
+ )
+
+ enabled = await database_sync_to_async_pool(is_deltalite_shadow_enabled)(
+ self._job.team_id, str(self._job.schema_id), None
+ )
+ if not enabled:
+ return
+
+ 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,
+ )
+ except Exception as e: # noqa: BLE001 - shadow must never affect the sync
+ await self._logger.awarning(f"deltalite shadow wrapper errored (ignored): {e}")
+
async def write_to_deltalake(
self,
data: pa.Table,
@@ -529,6 +572,10 @@ 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
@@ -618,6 +665,26 @@ 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
new file mode 100644
index 000000000000..185442217b65
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_shadow.py
@@ -0,0 +1,408 @@
+"""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/test/test_deltalite_shadow.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_shadow.py
new file mode 100644
index 000000000000..a889d36c7390
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_shadow.py
@@ -0,0 +1,273 @@
+"""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/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
index 3d29224a8082..90252361136f 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
@@ -46,3 +46,20 @@ DELTA_REPARTITION_SKIP_TOTAL = Counter(
"Tables over the partition-size budget that the controller skipped, by reason",
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",
+ labelnames=["outcome"],
+)
+
+DELTALITE_SHADOW_DURATION_SECONDS = Histogram(
+ "warehouse_load_deltalite_shadow_duration_seconds",
+ "Wall-clock time of a deltalite shadow verification (seed + upsert + compare)",
+)
diff --git a/pyproject.toml b/pyproject.toml
index 47f4f1e06e1e..bb50d3918c96 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -200,6 +200,7 @@ dependencies = [
"braintrust-core>=0.0.59,<1",
"wrapt==1.17.3",
"limits==5.8.0",
+ "deltalite==0.1.1",
]
[dependency-groups]
@@ -293,7 +294,7 @@ hogql-parser-parity = [
required-version = ">=0.10.2"
add-bounds = "major"
exclude-newer = "7 days"
-exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, posthoganalytics = false, pixelhog = false, django = false, modal = false, posthog-hogland = false, google-ads = false }
+exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, deltalite = false, posthoganalytics = false, pixelhog = false, django = false, modal = false, posthog-hogland = false, google-ads = false }
[tool.uv.workspace]
members = ["tools/hogli", "tools/owners"]
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 845f3c573174..2fef29672122 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3786,7 +3786,7 @@ dependencies = [
[[package]]
name = "deltalite-python"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"arrow",
"arrow-array",
diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.toml
index 97503b4feb3b..802586f133c3 100644
--- a/rust/deltalite/python/Cargo.toml
+++ b/rust/deltalite/python/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "deltalite-python"
# Mirrors pyproject.toml in this directory (always identical); bump both together.
-version = "0.1.0"
+version = "0.1.1"
edition = "2021"
# CI compiles with this exact toolchain; cargo's MSRV-aware resolver uses it to
# avoid picking dependency versions CI cannot build (aws-* crates move MSRV often).
diff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.toml
index f427577e7760..3ac612bdb2b1 100644
--- a/rust/deltalite/python/pyproject.toml
+++ b/rust/deltalite/python/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "maturin"
[project]
name = "deltalite"
# Mirrors `rust/deltalite/python/Cargo.toml` (always identical); bump both together.
-version = "0.1.0"
+version = "0.1.1"
description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"
readme = "README.md"
requires-python = ">=3.12"
diff --git a/uv.lock b/uv.lock
index 46d32c553a53..651f910d1cec 100644
--- a/uv.lock
+++ b/uv.lock
@@ -20,6 +20,7 @@ modal = false
posthoganalytics = false
django = false
google-ads = false
+deltalite = false
hogql-parser = false
posthog-hogland = false
hogql-parser-rs = false
@@ -1728,6 +1729,20 @@ pyarrow = [
{ name = "pyarrow" },
]
+[[package]]
+name = "deltalite"
+version = "0.1.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c4/eb/294ae8238a492a8751782c505e4f1baa03c988a18fe2b4d8f27024af3656/deltalite-0.1.1.tar.gz", hash = "sha256:a36666ed4916bca754be649fca418d43536c75e99b8236bd742296cae502e444", size = 164828, upload-time = "2026-07-28T22:11:22.704Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b4/1f/5b0c37e0ad68aba0744140d4d99b40285f97d53a1d263bbfbcb7c706789f/deltalite-0.1.1-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:ce05c3ceb0c66d5e1fa6067cafd54416fc7b72547d1f833dd70e31ff4ffae4e1", size = 17954501, upload-time = "2026-07-28T22:10:59.924Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/4d/3fdda303726b7005a2383b4681e9d3df5f8b63e2c019c2c75ed21b245e2e/deltalite-0.1.1-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:801a7eada9de6143831e0d06ada42daea584e6ccc7262884a816f5e7a6420d06", size = 17835888, upload-time = "2026-07-28T22:11:02.949Z" },
+ { url = "https://files.pythonhosted.org/packages/73/da/e084d26f656e71b583a99f7dda4770496cf3e8ee8a4503390f5b81c4480e/deltalite-0.1.1-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ef9f8e6f3d07aaa8939e9d4d0bbc099059e3f9e25df3d1599fd6823f3e339ac1", size = 63131234, upload-time = "2026-07-28T22:11:06.931Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/fb/c465ff56c9b5075b9897b656df96b1d0f8105698c6d8f7707590f9a3d5ae/deltalite-0.1.1-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7e86ac4ecce2cf9afd41c24f38e995870affc2f1499eb36fe5d9df4593ada715", size = 65438702, upload-time = "2026-07-28T22:11:11.32Z" },
+ { url = "https://files.pythonhosted.org/packages/75/5d/9fb91fa0effadcb0b42c4c4f374e90c1c5af31a083d26cfbbc04fd5fcab0/deltalite-0.1.1-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0b270ad5c1b522a0539476a88a8a3037338c6be0a53f90e28c58921c136526fa", size = 62717513, upload-time = "2026-07-28T22:11:15.663Z" },
+ { url = "https://files.pythonhosted.org/packages/39/9f/6d52ffa7d8a98b66c3dc28a7b0d00873cd936dac894de4094073e8996764/deltalite-0.1.1-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3d944bc32404721036225dfbad0fb611a16075650b6bf58c0eeb23e86ff4c6a4", size = 63791320, upload-time = "2026-07-28T22:11:20.172Z" },
+]
+
[[package]]
name = "deprecated"
version = "1.2.18"
@@ -5567,6 +5582,7 @@ dependencies = [
{ name = "databricks-sql-connector" },
{ name = "defusedxml" },
{ name = "deltalake", extra = ["pyarrow"] },
+ { name = "deltalite" },
{ name = "disposable-email-domains" },
{ name = "dj-database-url" },
{ name = "django" },
@@ -5843,6 +5859,7 @@ requires-dist = [
{ name = "databricks-sql-connector", specifier = "~=4.3.0" },
{ name = "defusedxml", specifier = "~=0.7.1" },
{ name = "deltalake", extras = ["pyarrow"], specifier = "==1.6.1" },
+ { name = "deltalite", specifier = "==0.1.1" },
{ name = "disposable-email-domains", specifier = "~=0.0.140" },
{ name = "dj-database-url", specifier = "~=3.0.0" },
{ name = "django", specifier = "~=5.2.0" },