:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(data-warehouse): remove the deltalite write rollout flag (#106874)
Tom Owersb5218ef3e633
diff --git a/products/data_warehouse/backend/s3_proxy.py b/products/data_warehouse/backend/s3_proxy.pyindex 53dc88b55214..e1100d1d69cb 100644--- a/products/data_warehouse/backend/s3_proxy.py+++ b/products/data_warehouse/backend/s3_proxy.py@@ -93,7 +93,7 @@ def warehouse_bucket_host() -> str | None:def _flag_enabled(_interval: int) -> bool:"""Evaluate the rollout flag, keyed on a time bucket so the cache expires on its own.- Any evaluation failure returns False (fail closed, as in ``is_deltalite_write_enabled``): a flags+ Any evaluation failure returns False (fail closed): a flags-service blip leaves traffic on the proxy rather than silently rerouting it."""try:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.pyindex ef9a1cd540bc..61598121d0d1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/auto_widen_resync.py@@ -56,7 +56,7 @@ def is_auto_widen_resync_enabled(team_id: int, schema_id: str, source_type: str``schema_id`` / ``team_id`` / ``source_type`` are passed as person properties so the flag can bereleased to a single table first (release condition ``schema_id = <id>``) before ramping by team /- org / source. Mirrors ``is_deltalite_write_enabled``. This flag is the only control (no env+ org / source. This flag is the only control (no envswitch), so recovery can be ramped or killed from the flag UI without a deploy. Any evaluationfailure returns False (fail closed): a flags-service blip must never accidentally switch it on."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.pyindex 4284b3d4263b..59db8d733744 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py@@ -107,6 +107,25 @@ def _make_writer() -> DeltaWriter:return DeltaWriter(DeltaTableRef(resource_name="t", job=MagicMock(), logger=make_logger()))+# `deltalite` is a real dependency here (unlike a flag-off rollout, its import always succeeds),+# so every primary-keyed `write()` call below would otherwise drive the real package instead of+# the delta-rs MERGE path most of these tests are actually about. Default it off; the classes that+# exist specifically to exercise deltalite opt back in (`TestDeltaliteWritePath` drives the real+# method directly / fakes the `deltalite` module itself, and `TestNullabilityDriftGuardOrder`+# already sets this mock explicitly in both directions).+_DELTALITE_OPT_IN_CLASSES = {"TestDeltaliteWritePath", "TestNullabilityDriftGuardOrder"}++[email protected](autouse=True)+def _default_deltalite_to_merge_fallback(request: pytest.FixtureRequest):+ cls = request.node.cls+ if cls is not None and cls.__name__ in _DELTALITE_OPT_IN_CLASSES:+ yield+ return+ with patch.object(DeltaWriter, "_write_via_deltalite", AsyncMock(return_value=False)):+ yield++class TestHasCommitWithMetadata:@pytest.mark.asyncioasync def test_returns_false_when_no_delta_table(self):@@ -264,10 +283,14 @@ class TestNullabilityDriftGuardOrder:self._seed_non_nullable_table(delta_path)helper = make_local_table_ref(delta_path)- # deltalite is off (the flag evaluation fails closed in tests), so the write falls- # through to the MERGE, which would silently store the nulls under a schema that- # denies them -- the guard must stop it with the reset signal instead.- with pytest.raises(SchemaColumnTypeChangedException, match="now contains nulls"):+ # Force the delta-rs MERGE fallback. deltalite now handles every keyed incremental+ # merge, so this path is only reached when deltalite declines or fails -- and the+ # MERGE would silently store the nulls under a schema that denies them, so the+ # guard must stop it with the reset signal instead.+ with (+ patch.object(DeltaWriter, "_write_via_deltalite", AsyncMock(return_value=False)),+ pytest.raises(SchemaColumnTypeChangedException, match="now contains nulls"),+ ):await DeltaWriter(helper).write(data=self._null_carrying_batch(),write_type="incremental",@@ -945,13 +968,8 @@ class TestNullSafeMergePredicate: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"- )+ """deltalite performs every keyed incremental merge, with a hard fallback to the delta-rs MERGE+ so a deltalite failure can never fail a sync."""@pytest.fixture(autouse=True)def _preload_write_metrics(self):@@ -980,17 +998,15 @@ class TestDeltaliteWritePath:@pytest.mark.asyncioasync 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 DeltaWriter(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,- )+ # No primary keys => nothing to key an upsert on; fall back to the delta-rs MERGE.+ wrote = await DeltaWriter(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()def test_write_stats_flattens_scalar_getters_only(self):# Enumerates scalar attributes (so future crate fields flow through) and drops methods/non-scalars.@@ -998,11 +1014,6 @@ class TestDeltaliteWritePath:stats.helper = lambda: None # callable attribute must be ignoredassert _deltalite_write_stats(stats) == {"version": 7, "rows_inserted": 2, "files_added": 1}- @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.asyncioasync def test_writes_via_deltalite_when_enabled(self):logger = make_logger() # captured so we can inspect the structured log without hitting the typed attr@@ -1017,7 +1028,6 @@ class TestDeltaliteWritePath:fake_deltalite = MagicMock()fake_deltalite.DeltaLiteTable.open.return_value = fake_tablewith (- 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"}),@@ -1051,7 +1061,6 @@ class TestDeltaliteWritePath:fake_deltalite = MagicMock()fake_deltalite.DeltaLiteTable.open.return_value = fake_tablewith (- 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={}),@@ -1076,7 +1085,6 @@ class TestDeltaliteWritePath:fake_deltalite = MagicMock()fake_deltalite.DeltaLiteTable.open.return_value = fake_tablewith (- 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={}),diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.pyindex e0050de6a3fe..98b329a2353a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py@@ -11,7 +11,6 @@ import pyarrow.compute as pcimport deltalake.exceptionsfrom posthog.exceptions_capture import capture_exception-from posthog.sync import database_sync_to_async_poolfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (MISSING_PRIMARY_KEYS_ERROR,@@ -160,34 +159,21 @@ class DeltaWriter:use_partitioning: bool,commit_metadata: dict[str, str] | None,) -> bool:- """Phase 2: perform the incremental merge via deltalite instead of the delta-rs MERGE.+ """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.+ to fall back to the MERGE. Falls back on *anything* — import failure, deltalite error / commit+ conflict / refusal — so deltalite can only change which engine writes, never whether the sync+ succeeds; the worst case is the delta-rs behaviour that predates it.++ Every incremental merge with primary keys now goes through here. The rollout flag this used to+ consult was evaluated on the hot path before every merge — two Postgres queries plus a+ non-local ``feature_enabled`` call per batch — and is gone."""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_write import (- is_deltalite_write_enabled,- )-- enabled = await database_sync_to_async_pool(is_deltalite_write_enabled)(- self._table.job.team_id, str(self._table.job.schema_id), None- )- except Exception: # noqa: BLE001 - a flag-eval / import error just means "don't use deltalite"- return False- if not enabled:- return False-- # deltalite is enabled. Only the upsert *commit* gates the fallback: a pre-commit failure means+ # 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 modulediff --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.pydeleted file mode 100644index 176b8f873214..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/deltalite_write.py+++ /dev/null@@ -1,62 +0,0 @@-"""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-``DeltaWriter._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 Falsediff --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.pydeleted file mode 100644index d422baf8933b..000000000000--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_deltalite_write.py+++ /dev/null@@ -1,57 +0,0 @@-"""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/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex c694e5cadb7b..b1af17245007 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -75,6 +75,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_jobfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenancefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import DeltaWriterfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLTfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (process_message,@@ -3059,6 +3060,10 @@ async def test_partition_folders_delta_merge_called_with_partition_predicate("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor.run_post_load_operations",new_callable=AsyncMock,) as mock_v3_post_load,+ # This test asserts on the delta-rs MERGE call itself (predicate, call count), so force+ # the fallback: deltalite has no rollout gate any more and would otherwise handle the+ # merge for real, and the MERGE below would never be called.+ mock.patch.object(DeltaWriter, "_write_via_deltalite", AsyncMock(return_value=False)),):# Mocking the return of the delta merge as it gets JSON'ifiedmock_merge_instance = mock_merge.return_value