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.

fix(snowflake): Include batch export id in table stage prefix (#74944)

Tomás Farías Santana5ba43df83e9d
diff --git a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
index f647d49bf34b..babe8fafa4b2 100644
--- a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
@@ -995,7 +995,7 @@ class SnowflakeClient:
self,
file: BatchExportTemporaryFile | NamedBytesIO,
table: SnowflakeTable,
- ):
+ ) -> None:
"""Executes a PUT query using the provided cursor to the provided table_name.
Sadly, Snowflake's execute_async does not work with PUT statements. So, we pass the execute
@@ -1454,7 +1454,7 @@ async def insert_into_snowflake_activity_from_stage(
database=inputs.database,
primary_key=merge_settings.primary_key if merge_settings else (),
version_key=merge_settings.version_key if merge_settings else (),
- stage_prefix=data_interval_end_str,
+ stage_prefix=f"{inputs.batch_export_id}/{data_interval_end_str}",
)
if "elements" in target_table:
# `elements` is exported into a 'VARIANT' column, despite it being a
diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.py
index 8ace162d9c83..31c511c31f7a 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_activity_e2e.py
@@ -68,6 +68,7 @@ async def _run_activity(
extra_fields: dict[str, t.Any] | None = None,
min_ingested_timestamp: dt.datetime | None = None,
integration_id: int | None = None,
+ batch_export_id: str | None = None,
):
"""Helper function to run insert_into_snowflake_activity_from_stage and assert records in Snowflake"""
config = dict(snowflake_config)
@@ -84,7 +85,7 @@ async def _run_activity(
exclude_events=exclude_events,
batch_export_schema=batch_export_schema,
batch_export_model=batch_export_model,
- batch_export_id=str(uuid.uuid4()),
+ batch_export_id=batch_export_id or str(uuid.uuid4()),
integration_id=integration_id,
**config,
)
@@ -431,7 +432,7 @@ async def test_insert_into_snowflake_activity_removes_internal_stage_files(
model = BatchExportModel(name="events", schema=None)
table_name = f"test_insert_activity_table_remove_{ateam.pk}"
min_ingested_timestamp = dt.datetime.now(dt.UTC).replace(tzinfo=None)
-
+ batch_export_id = str(uuid.uuid4())
await _run_activity(
activity_environment=activity_environment,
snowflake_cursor=snowflake_cursor,
@@ -444,6 +445,7 @@ async def test_insert_into_snowflake_activity_removes_internal_stage_files(
batch_export_model=model,
sort_key="event",
min_ingested_timestamp=min_ingested_timestamp,
+ batch_export_id=batch_export_id,
)
snowflake_cursor.execute(f'TRUNCATE TABLE "{table_name}"')
@@ -451,7 +453,7 @@ async def test_insert_into_snowflake_activity_removes_internal_stage_files(
data_interval_end_str = data_interval_end.strftime("%Y-%m-%d_%H-%M-%S")
put_query = f"""
- PUT file://{garbage_jsonl_file} '@%"{table_name}"/{data_interval_end_str}'
+ PUT file://{garbage_jsonl_file} '@%"{table_name}"/{batch_export_id}/{data_interval_end_str}'
"""
snowflake_cursor.execute(put_query)
@@ -463,7 +465,9 @@ async def test_insert_into_snowflake_activity_removes_internal_stage_files(
columns = {index: metadata.name for index, metadata in enumerate(snowflake_cursor.description)}
stage_files = [{columns[index]: row[index] for index in columns.keys()} for row in rows]
assert len(stage_files) == 1
- assert stage_files[0]["name"] == f"{data_interval_end_str}/{os.path.basename(garbage_jsonl_file)}.gz"
+ assert (
+ stage_files[0]["name"] == f"{batch_export_id}/{data_interval_end_str}/{os.path.basename(garbage_jsonl_file)}.gz"
+ )
await _run_activity(
activity_environment=activity_environment,
@@ -477,6 +481,7 @@ async def test_insert_into_snowflake_activity_removes_internal_stage_files(
batch_export_model=model,
sort_key="event",
min_ingested_timestamp=min_ingested_timestamp,
+ batch_export_id=batch_export_id,
)
snowflake_cursor.execute(list_query)
diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_client.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_client.py
index bb2332c03161..4d1e7d50a33a 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_client.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_client.py
@@ -5,6 +5,7 @@ Note: This module uses a real Snowflake connection.
"""
import os
+import uuid
import asyncio
import datetime as dt
@@ -12,8 +13,10 @@ import pytest
import pyarrow as pa
import pytest_asyncio
+import pyarrow.parquet as pq
from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import (
+ NamedBytesIO,
SnowflakeClient,
SnowflakeField,
SnowflakeIncompatibleSchemaError,
@@ -244,3 +247,106 @@ async def test_get_table_raises_incompatible_schema_on_missing_version_key_field
assert "'missing_key_one'" in str(excinfo.value)
assert "'missing_key_two'" in str(excinfo.value)
+
+
+async def test_put_file_to_snowflake_table_stage(snowflake_client, database, schema, test_table):
+ """Test files are put into Snowflake table stage."""
+ test_table.stage_prefix = f"{str(uuid.uuid4())}/{dt.datetime.now(dt.UTC):%Y-%m-%d_%H-%M-%S}"
+
+ n_legs = pa.array([2, 2, 4, 4, 5, 100])
+ animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
+ table = pa.Table.from_arrays([n_legs, animals], names=["id", "text"])
+ file_like = NamedBytesIO(b"", name="test_file")
+ pq.write_table(table, file_like)
+
+ file_like.seek(0)
+ await snowflake_client.put_file_to_snowflake_table_stage(file_like, test_table)
+
+ result = await snowflake_client.execute_async_query(
+ f"""
+ LIST '@%"{test_table.name}"/{test_table.stage_prefix}'
+ """,
+ timeout=60.0,
+ )
+ assert result is not None, "Expected at least one file"
+
+ rows, metadata = result
+ assert len(rows) == 1, "Expected only one file"
+
+ row = rows[0]
+ row_dict = dict(zip((field.name for field in metadata), row))
+ assert row_dict["name"] == f"{test_table.stage_prefix}/test_file"
+
+
+async def test_copy_loaded_files_to_snowflake_table_only_works_on_stage_prefix(
+ snowflake_client, database, schema, test_table
+):
+ """Test copying only copies and purges files under stage prefix.
+
+ This ensures that multiple COPY queries to the same table do not PURGE or
+ COPY each other files.
+ """
+ test_table.stage_prefix = first_prefix = f"{str(uuid.uuid4())}/{dt.datetime.now(dt.UTC):%Y-%m-%d_%H-%M-%S}"
+
+ ids = [2, 2, 4, 4, 5, 100]
+ text = ["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]
+ n_legs = pa.array(ids)
+ animals = pa.array(text)
+ table = pa.Table.from_arrays([n_legs, animals], names=["id", "text"])
+ file_like = NamedBytesIO(b"", name="test_file")
+ pq.write_table(table, file_like)
+
+ file_like.seek(0)
+ await snowflake_client.put_file_to_snowflake_table_stage(file_like, test_table)
+
+ # Same file, different prefix
+ file_like.seek(0)
+ test_table.stage_prefix = second_prefix = f"{str(uuid.uuid4())}/{dt.datetime.now(dt.UTC):%Y-%m-%d_%H-%M-%S}"
+ await snowflake_client.put_file_to_snowflake_table_stage(file_like, test_table)
+
+ await snowflake_client.copy_loaded_files_to_snowflake_table(test_table, timeout=30.0)
+
+ # Check data was actually copied
+ result = await snowflake_client.execute_async_query(
+ f"""
+ SELECT * FROM "{test_table.name}"
+ """,
+ timeout=60.0,
+ )
+ assert result is not None, "Expected at least one row in table was copied"
+
+ rows, metadata = result
+ data: dict[str, list[int] | list[str]] = {"id": [], "text": []}
+ for row in rows:
+ dict_row = dict(zip((field.name for field in metadata), row))
+ data["id"].append(dict_row["id"])
+ data["text"].append(dict_row["text"])
+
+ assert sorted(data["id"]) == sorted(ids)
+ assert sorted(data["text"]) == sorted(text)
+
+ # Check that first prefix file should still be there
+ result = await snowflake_client.execute_async_query(
+ f"""
+ LIST '@%"{test_table.name}"/{first_prefix}'
+ """,
+ timeout=60.0,
+ )
+ assert result is not None, "Expected at least one file"
+
+ rows, metadata = result
+ assert len(rows) == 1, "Expected only one file"
+
+ row = rows[0]
+ row_dict = dict(zip((field.name for field in metadata), row))
+ assert row_dict["name"] == f"{first_prefix}/test_file"
+
+ # Check that second prefix file should have been purged by COPY
+ result = await snowflake_client.execute_async_query(
+ f"""
+ LIST '@%"{test_table.name}"/{second_prefix}'
+ """,
+ timeout=60.0,
+ )
+ rows, metadata = result
+ assert rows == []
diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py
index a19b798908f2..b2c59509b911 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py
@@ -180,11 +180,15 @@ async def test_snowflake_export_workflow_exports_events(
assert all(query.startswith("PUT") for query in execute_calls[0:9])
assert execute_async_calls[5].startswith(f'SELECT * FROM "{table_name}" LIMIT 0')
- assert execute_async_calls[6].startswith(f"""REMOVE '@%"{table_name}"/{data_interval_end_str}'""")
+ assert execute_async_calls[6].startswith(
+ f"""REMOVE '@%"{table_name}"/{snowflake_batch_export.id}/{data_interval_end_str}'"""
+ )
assert execute_async_calls[7].startswith(f'CREATE TABLE IF NOT EXISTS "{table_name}"')
assert execute_async_calls[8].startswith(f'SELECT * FROM "{table_name}" LIMIT 0')
assert execute_async_calls[9].startswith(f'COPY INTO "{table_name}"')
- assert execute_async_calls[10].startswith(f"""REMOVE '@%"{table_name}"/{data_interval_end_str}'""")
+ assert execute_async_calls[10].startswith(
+ f"""REMOVE '@%"{table_name}"/{snowflake_batch_export.id}/{data_interval_end_str}'"""
+ )
@pytest.mark.parametrize("interval", ["hour"], indirect=True)