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): skip unnecessary delta table fetch in pipeline cleanup (#74378)

Tom Owers5870b06bc6c2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
index ed5bdbb2394d..03dd583b01f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
@@ -1206,8 +1206,22 @@ def conditional_lru_cache_async(
key = _make_key(args, kwargs, typed)
cache.pop(key, None)
+ def cache_pop(*args, **kwargs) -> Any:
+ """Remove and return a cached value without ever invoking `func` — unlike calling
+ `wrapper` itself, a cache miss returns `None` instead of computing and storing a
+ fresh result. For callers that only want to release an already-cached resource.
+
+ Checks membership before popping: CircularDict.pop(key, None) treats a `None`
+ default as "no default" and raises KeyError on a miss instead of returning it.
+ """
+ key = _make_key(args, kwargs, typed)
+ if key not in cache:
+ return None
+ return cache.pop(key)
+
cast(Any, wrapper).cache_remove = cache_remove
cast(Any, wrapper).cache_clear = lambda: cache.clear()
+ cast(Any, wrapper).cache_pop = cache_pop
return wrapper
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 073409863465..4f258ec8f047 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
_to_list_array,
align_incoming_decimals_to_delta,
apply_enabled_columns_projection,
+ conditional_lru_cache_async,
evolve_pyarrow_schema,
merge_observed_columns_into_schema_metadata,
normalize_table_column_names,
@@ -1528,3 +1529,33 @@ def test_billing_limit_exception_is_non_reportable_error():
# Subclassing NonReportableError is what keeps the intentional billing-limit halt out of
# error tracking (the activity interceptor re-raises these without capturing them).
assert issubclass(BillingLimitsWillBeReachedException, NonReportableError)
+
+
+class TestConditionalLruCacheAsyncCachePop:
+ @pytest.mark.asyncio
+ async def test_pop_on_cache_miss_returns_none_without_calling_func(self):
+ # A best-effort cleanup path (e.g. releasing an already-fetched delta table) must be able
+ # to check the cache without ever triggering the wrapped function's own I/O — a miss here
+ # used to mean "call the real function", which made cleanup do an unrelated object-storage
+ # call and risk masking the real error with a fresh, spurious one.
+ calls = []
+
+ @conditional_lru_cache_async(maxsize=1)
+ async def fetch(key: str) -> str:
+ calls.append(key)
+ return f"value-{key}"
+
+ assert fetch.cache_pop("a") is None
+ assert calls == []
+
+ @pytest.mark.asyncio
+ async def test_pop_on_cache_hit_returns_and_removes_cached_value(self):
+ @conditional_lru_cache_async(maxsize=1)
+ async def fetch(key: str) -> str:
+ return f"value-{key}"
+
+ assert await fetch("a") == "value-a"
+
+ assert fetch.cache_pop("a") == "value-a"
+ # Popped, not just read — a second pop finds nothing left to remove.
+ assert fetch.cache_pop("a") is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
index 47c508891a43..2336c0b2bf3a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
@@ -282,19 +282,16 @@ class PipelineNonDLT(Generic[ResumableData]):
result["prepared_queryable_folder"] = prepared_queryable_folder
return result
finally:
- # Help reduce the memory footprint of each job. This is best-effort cleanup:
- # `get_delta_table` does object-storage I/O, so a transient storage blip here
- # must not mask the real import error from the try body — which drives
- # retry classification and the user-facing message — nor fail an otherwise
- # successful sync.
+ # Help reduce the memory footprint of each job. This is best-effort cleanup of
+ # whatever `get_delta_table` already cached this run — pop rather than call, so a
+ # run that failed before ever fetching the delta table (nothing to release) doesn't
+ # make a fresh, unrelated object-storage call here that can itself raise and get
+ # captured, obscuring the real import error that's already driving retry
+ # classification and the user-facing message.
await self._logger.adebug("Cleaning up delta table helper")
- try:
- delta_table = await self._delta_table_helper.get_delta_table()
- self._delta_table_helper.get_delta_table.cache_clear()
- if delta_table:
- del delta_table
- except Exception:
- await self._logger.aexception("Failed to clean up delta table helper")
+ delta_table = self._delta_table_helper.get_delta_table.cache_pop(self._delta_table_helper)
+ if delta_table:
+ del delta_table
del self._resource
del self._delta_table_helper
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
index 6ffb50d90f57..f3b891e33149 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
@@ -15,19 +15,22 @@ _PIPELINE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pip
@pytest.mark.asyncio
-async def test_run_cleanup_failure_does_not_mask_import_error(monkeypatch):
- # Regression: run()'s finally calls get_delta_table() (object-storage I/O) purely for
- # memory cleanup. When that raised — e.g. a transient object-storage blip — it replaced
- # the in-flight import error, so a connection failure already classified as non-retryable
+async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_import_error(monkeypatch):
+ # Regression: run()'s finally used to call get_delta_table() (object-storage I/O) purely for
+ # memory cleanup, even on a run that failed before ever fetching a delta table (nothing
+ # cached, nothing to clean up). A transient object-storage blip on that spurious call then
+ # replaced the in-flight import error, so a failure already classified as non-retryable
# surfaced as the unrelated cleanup error and the job retried to its maximum instead of
- # stopping. The body error must propagate; the cleanup error must be swallowed.
+ # stopping. Cleanup must pop whatever's cached instead of recomputing it, so it can no
+ # longer make its own object-storage call at all.
pipeline = PipelineNonDLT.__new__(PipelineNonDLT)
pipeline._logger = AsyncMock()
pipeline._resumable_source_manager = None
pipeline._cdp_producer = cast(CDPProducer, object()) # unused: the patched clear-chunks ignores it
pipeline._resource = cast(SourceResponse, object())
- pipeline._delta_table_helper = AsyncMock()
- pipeline._delta_table_helper.get_delta_table.side_effect = OSError("object storage unavailable")
+ delta_table_helper = AsyncMock()
+ delta_table_helper.get_delta_table.cache_pop.return_value = None
+ pipeline._delta_table_helper = delta_table_helper
class ImportError_(Exception):
pass
@@ -43,7 +46,10 @@ async def test_run_cleanup_failure_does_not_mask_import_error(monkeypatch):
with pytest.raises(ImportError_, match="Can't connect to MySQL server on"):
await pipeline.run()
- pipeline._logger.aexception.assert_awaited_once_with("Failed to clean up delta table helper")
+ # run()'s finally `del self._delta_table_helper`s afterward, so assert on the captured
+ # reference rather than re-reading it off `pipeline`.
+ delta_table_helper.get_delta_table.assert_not_called()
+ delta_table_helper.get_delta_table.cache_pop.assert_called_once_with(delta_table_helper)
def _make_pipeline_for_post_run_operations() -> PipelineNonDLT: