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(data-imports): retry queryable-table copy when a source file vanishes mid-compaction (#82460)

Tom Owers4ea1a28ca286
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index e2b679513f41..c9e5ebfc2988 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -197,7 +197,7 @@ def _build_model_table_uri(team_id: int, saved_query_id_hex: str, normalized_nam
return f"{settings.BUCKET_URL}/team_{team_id}_model_{saved_query_id_hex}/modeling/{normalized_name}"
-def _get_aws_storage_options() -> dict[str, str]:
+def get_aws_storage_options() -> dict[str, str]:
if settings.USE_LOCAL_SETUP:
ensure_bucket_exists(
settings.BUCKET_URL,
@@ -815,7 +815,7 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
table_uri = _build_model_table_uri(objects.team.pk, objects.saved_query.id.hex, objects.saved_query.normalized_name)
await logger.adebug(f"Delta table URI = {table_uri}")
- storage_options = _get_aws_storage_options()
+ storage_options = get_aws_storage_options()
plan = await _resolve_write_plan(objects.saved_query, inputs.team_id)
if plan.incremental and not await asyncio.to_thread(table_exists, table_uri, storage_options):
# deltalite can only open a table, never create one, so a missing table has to rebuild.
diff --git a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
index a64e8d89d16f..d35e06c2f801 100644
--- a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
+++ b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py
@@ -1,9 +1,12 @@
+import asyncio
import dataclasses
+import deltalake
from structlog import get_logger
from temporalio import activity
from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.data_modeling.activities.materialize_view import get_aws_storage_options
from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_context
from products.data_modeling.backend.facade.api import promote_view_nodes_to_matview
@@ -57,6 +60,11 @@ def _update_saved_query_with_table(
promote_view_nodes_to_matview(saved_query)
+async def _refresh_file_uris(table_uri: str) -> list[str]:
+ storage_options = get_aws_storage_options()
+ return await asyncio.to_thread(lambda: deltalake.DeltaTable(table_uri, storage_options=storage_options).file_uris())
+
+
@dataclasses.dataclass
class PrepareQueryableTableResult:
storage_delta_mib: float | None
@@ -87,6 +95,7 @@ async def _stage_files(inputs: PrepareQueryableTableInputs, saved_query: DataWar
preserve_table_name_casing=True,
existing_queryable_folder=queryable_folder,
logger=logger,
+ refresh_file_uris=lambda: _refresh_file_uris(inputs.table_uri),
)
diff --git a/posthog/temporal/data_modeling/run_workflow.py b/posthog/temporal/data_modeling/run_workflow.py
index 7f589ae3ed78..3cb4eea24a41 100644
--- a/posthog/temporal/data_modeling/run_workflow.py
+++ b/posthog/temporal/data_modeling/run_workflow.py
@@ -725,6 +725,11 @@ async def materialize_model(
preserve_table_name_casing=True,
existing_queryable_folder=saved_query_table.queryable_folder if saved_query_table else None,
logger=logger,
+ # Reopen the table instead of reusing this snapshot: a concurrent compaction can advance the
+ # log after `delta_table` loaded, so the retry needs the listing that log now holds.
+ refresh_file_uris=lambda: asyncio.to_thread(
+ lambda: deltalake.DeltaTable(table_uri, storage_options=storage_options).file_uris()
+ ),
)
saved_query.is_materialized = True
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index e386969c6559..44e92bce7dc8 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -36,7 +36,7 @@ from posthog.temporal.data_modeling.activities import (
from posthog.temporal.data_modeling.activities.materialize_view import (
LOGGER,
InvalidNodeTypeException,
- _get_aws_storage_options,
+ get_aws_storage_options,
get_s3_client,
hogql_table,
)
@@ -1192,6 +1192,55 @@ class TestPrepareQueryableTableActivity:
)
await database_sync_to_async(warehouse_table.delete)()
+ async def test_passes_refresh_file_uris_that_re_reads_the_delta_table(
+ self, activity_environment, ateam, asaved_query, ajob
+ ):
+ # Regression: this call site used to omit refresh_file_uris, so a source file a concurrent
+ # compact/vacuum pass deleted mid-copy raised FileNotFoundError straight through instead of
+ # retrying with a fresh listing (see prepare_s3_files_for_querying's vanished-file handling).
+ inputs = PrepareQueryableTableInputs(
+ team_id=ateam.pk,
+ job_id=str(ajob.id),
+ saved_query_id=str(asaved_query.id),
+ table_uri="s3://test-bucket/test_table",
+ file_uris=["s3://test-bucket/test_file.parquet"],
+ row_count=100,
+ )
+ warehouse_table = await database_sync_to_async(DataWarehouseTable.objects.create)(
+ team=ateam,
+ name="test_warehouse_table",
+ format="Delta",
+ )
+ refreshed_file_uris = ["s3://test-bucket/test_table/compacted.parquet"]
+ mock_delta_table = unittest.mock.MagicMock()
+ mock_delta_table.file_uris.return_value = refreshed_file_uris
+ with (
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.prepare_queryable_table.prepare_s3_files_for_querying"
+ ) as mock_prepare,
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.prepare_queryable_table.create_table_from_saved_query"
+ ) as mock_create_table,
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.prepare_queryable_table.get_aws_storage_options",
+ return_value={},
+ ),
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.prepare_queryable_table.deltalake.DeltaTable",
+ return_value=mock_delta_table,
+ ) as mock_delta_table_cls,
+ ):
+ mock_prepare.return_value = "test-bucket/queryable_folder"
+ mock_create_table.return_value = CreateTableResult(
+ table=warehouse_table, storage_delta_mib=None, total_storage_mib=None
+ )
+ await activity_environment.run(prepare_queryable_table_activity, inputs)
+
+ refresh_file_uris = mock_prepare.call_args.kwargs["refresh_file_uris"]
+ assert await refresh_file_uris() == refreshed_file_uris
+ mock_delta_table_cls.assert_called_once_with(inputs.table_uri, storage_options={})
+ await database_sync_to_async(warehouse_table.delete)()
+
async def test_updates_saved_query_with_table_reference(self, activity_environment, ateam, asaved_query, ajob):
inputs = PrepareQueryableTableInputs(
team_id=ateam.pk,
@@ -1411,7 +1460,7 @@ class TestMaterializeViewActivity:
result = await activity_environment.run(materialize_view_activity, inputs)
assert result.row_count == 6
- delta_table = deltalake.DeltaTable(result.table_uri, storage_options=_get_aws_storage_options())
+ delta_table = deltalake.DeltaTable(result.table_uri, storage_options=get_aws_storage_options())
materialized = delta_table.to_pyarrow_table()
assert materialized.column_names == camel_case_names
assert materialized.num_rows == 6
@@ -1466,7 +1515,7 @@ class TestMaterializeViewActivity:
result = await activity_environment.run(materialize_view_activity, inputs)
assert result.row_count == 6
- delta_table = deltalake.DeltaTable(result.table_uri, storage_options=_get_aws_storage_options())
+ delta_table = deltalake.DeltaTable(result.table_uri, storage_options=get_aws_storage_options())
materialized = delta_table.to_pyarrow_table()
assert materialized.column_names == camel_case_names
assert materialized.num_rows == 6
@@ -1516,7 +1565,7 @@ class TestMaterializeViewActivity:
assert len(result.file_uris) == 1
assert result.file_uris[0].endswith(".parquet")
# delta log carries the schema so deltaLake() reads in get_columns succeed
- delta_table = deltalake.DeltaTable(result.table_uri, storage_options=_get_aws_storage_options())
+ delta_table = deltalake.DeltaTable(result.table_uri, storage_options=get_aws_storage_options())
pyarrow_table = delta_table.to_pyarrow_table()
assert pyarrow_table.num_rows == 0
assert set(pyarrow_table.column_names) == {"id", "name"}
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
index c67847bad8e6..300defd74126 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
@@ -22,7 +22,7 @@ import deltalake
from posthog.sync import database_sync_to_async
from posthog.temporal.data_modeling.activities import MaterializeViewInputs, materialize_view_activity
from posthog.temporal.data_modeling.activities.incremental_write import IncrementalWriteError
-from posthog.temporal.data_modeling.activities.materialize_view import _get_aws_storage_options
+from posthog.temporal.data_modeling.activities.materialize_view import get_aws_storage_options
from products.data_modeling.backend.facade.api import get_incremental_state
@@ -45,7 +45,7 @@ def _batch(days: list[datetime | None], counts: list[int], *, value_column: str
def _rows(table_uri: str) -> list[tuple[Any, Any]]:
"""Stored rows as (day, value), sorted, so tests assert content rather than counts."""
- table = deltalake.DeltaTable(table_uri, storage_options=_get_aws_storage_options()).to_pyarrow_table()
+ table = deltalake.DeltaTable(table_uri, storage_options=get_aws_storage_options()).to_pyarrow_table()
value_column = next(name for name in table.column_names if name != "day")
pairs = list(zip(table.column("day").to_pylist(), table.column(value_column).to_pylist()))
return sorted(pairs, key=lambda pair: (pair[0] is None, pair[0]))
@@ -155,7 +155,7 @@ class TestIncrementalMaterialization:
# The returned file list is what the publish copies to S3 for querying. deltalite commits
# through its own handle, so a handle opened before the upserts would still name the
# pre-run files here and the published table would silently lose the run's writes.
- live = deltalake.DeltaTable(first.table_uri, storage_options=_get_aws_storage_options())
+ live = deltalake.DeltaTable(first.table_uri, storage_options=get_aws_storage_options())
assert sorted(second.file_uris) == sorted(live.file_uris())
await database_sync_to_async(asaved_query.refresh_from_db)()
@@ -220,7 +220,7 @@ class TestIncrementalMaterialization:
value_column="personId",
)
- table = deltalake.DeltaTable(first.table_uri, storage_options=_get_aws_storage_options())
+ table = deltalake.DeltaTable(first.table_uri, storage_options=get_aws_storage_options())
assert "personId" in table.to_pyarrow_table().column_names
assert _rows(first.table_uri) == [(DAY1, 10), (DAY2, 20)]