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): cache duckgres backfill snapshot plans for pinned Delta versions (#74121)

Tom Owers39ee695e303e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py
index 0cce77db925b..ff7428d5ec49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py
@@ -8,6 +8,8 @@ table's own live parquet files bounded by bytes and file count.
from __future__ import annotations
import json
+import threading
+from collections import OrderedDict
from dataclasses import dataclass
from typing import Any
from urllib.parse import unquote
@@ -94,9 +96,70 @@ def resolve_snapshot_chunks(schema: ExternalDataSchema, version: int | None = No
def resolve_snapshot_plan(schema: ExternalDataSchema, version: int | None = None) -> BackfillSnapshotPlan:
+ uri = delta_table_uri(schema)
+ if version is None:
+ # No pinned version to cache against — this is the initial plan, reading
+ # whatever HEAD currently is, which is not a stable cache key.
+ return _resolve_snapshot_plan(uri, version)
+ return _resolve_pinned_snapshot_plan(uri, version)
+
+
+# A cached plan holds every live parquet path and commit key for its table, so
+# entry *size* scales with table size — an entry-count cap alone doesn't bound
+# memory. Weigh entries by that count and cap the total instead: a plan over
+# budget on its own is simply never cached (recomputed every call, same as
+# before this cache existed), so one huge table can't make the cache retain an
+# unbounded amount indefinitely.
+_PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT = 50_000
+
+_pinned_snapshot_plan_cache: OrderedDict[tuple[str, int], tuple[BackfillSnapshotPlan, int]] = OrderedDict()
+_pinned_snapshot_plan_cache_weight = 0
+_pinned_snapshot_plan_cache_lock = threading.Lock()
+
+
+def _plan_weight(plan: BackfillSnapshotPlan) -> int:
+ return sum(len(chunk.paths) for chunk in plan.chunks) + len(plan.covered_batches)
+
+
+def _resolve_pinned_snapshot_plan(uri: str, version: int) -> BackfillSnapshotPlan:
+ """Cached for already-committed (pinned) versions only.
+
+ A commit at or before an already-resolved version never changes, but
+ deltalake's history() has no checkpoint shortcut — it walks the
+ _delta_log from genesis one commit at a time. The reconciler calls
+ resolve_snapshot_plan with the same pinned version on every ~30s tick
+ until a backfill finishes draining its queue, so without this cache a
+ large table (tens of thousands of commits) gets its entire commit log
+ re-read from S3 on every pass, which can trip S3 rate limiting.
+ """
+ global _pinned_snapshot_plan_cache_weight
+
+ key = (uri, version)
+ with _pinned_snapshot_plan_cache_lock:
+ cached = _pinned_snapshot_plan_cache.get(key)
+ if cached is not None:
+ _pinned_snapshot_plan_cache.move_to_end(key)
+ return cached[0]
+
+ plan = _resolve_snapshot_plan(uri, version)
+ weight = _plan_weight(plan)
+
+ with _pinned_snapshot_plan_cache_lock:
+ while (
+ _pinned_snapshot_plan_cache
+ and _pinned_snapshot_plan_cache_weight + weight > _PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT
+ ):
+ _, (_, evicted_weight) = _pinned_snapshot_plan_cache.popitem(last=False)
+ _pinned_snapshot_plan_cache_weight -= evicted_weight
+ if weight <= _PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT:
+ _pinned_snapshot_plan_cache[key] = (plan, weight)
+ _pinned_snapshot_plan_cache_weight += weight
+ return plan
+
+
+def _resolve_snapshot_plan(uri: str, version: int | None) -> BackfillSnapshotPlan:
from deltalake import DeltaTable
- uri = delta_table_uri(schema)
dt = DeltaTable(uri, version=version, storage_options=_delta_storage_options())
resolved_version = dt.version()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill_snapshot.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill_snapshot.py
index 226e327bad4e..f15da7ceb02a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill_snapshot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill_snapshot.py
@@ -1,4 +1,7 @@
import uuid
+from types import SimpleNamespace
+
+from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
@@ -7,6 +10,7 @@ from parameterized import parameterized
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import backfill_snapshot
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (
delta_table_uri,
)
@@ -74,3 +78,124 @@ class TestDeltaTableUri(SimpleTestCase):
assert uri.startswith(prefix)
leaf = uri[len(prefix) :]
assert "/" not in leaf and "." not in leaf and "%" not in leaf
+
+
+class _FakeColumn:
+ def __init__(self, values: list) -> None:
+ self._values = values
+
+ def to_pylist(self) -> list:
+ return self._values
+
+
+class _FakeAddActions:
+ def __init__(self, file_count: int = 1) -> None:
+ self._file_count = file_count
+
+ def column(self, name: str) -> _FakeColumn:
+ return {
+ "path": _FakeColumn([f"f{i}.parquet" for i in range(self._file_count)]),
+ "size_bytes": _FakeColumn([100] * self._file_count),
+ "num_records": _FakeColumn([10] * self._file_count),
+ }[name]
+
+
+class _FakeDeltaTable:
+ # Stands in for deltalake.DeltaTable: counts real constructions so the
+ # cache test can assert a pinned version's Delta log is read only once.
+ # file_count controls how many add-actions (and thus cache weight) a
+ # constructed instance reports, letting tests drive the weight budget.
+ instances = 0
+ file_count = 1
+
+ def __init__(self, uri: str, version: int | None = None, storage_options: dict | None = None) -> None:
+ _FakeDeltaTable.instances += 1
+ self._version = version if version is not None else 42
+
+ def version(self) -> int:
+ return self._version
+
+ def protocol(self) -> SimpleNamespace:
+ return SimpleNamespace(reader_features=[])
+
+ def get_add_actions(self, flatten: bool = True) -> _FakeAddActions:
+ return _FakeAddActions(_FakeDeltaTable.file_count)
+
+ def history(self) -> list[dict]:
+ return []
+
+
+@override_settings(BUCKET_URL="s3://test-bucket/dlt")
+class TestResolveSnapshotPlanCaching(SimpleTestCase):
+ # The reconciler re-resolves the same already-pinned snapshot_version on
+ # every tick until a backfill drains; without a cache each call re-reads
+ # the whole Delta commit log from S3 (dt.history() has no checkpoint
+ # shortcut), which for a large table can trip S3 rate limiting.
+ def setUp(self) -> None:
+ backfill_snapshot._pinned_snapshot_plan_cache.clear()
+ backfill_snapshot._pinned_snapshot_plan_cache_weight = 0
+ _FakeDeltaTable.instances = 0
+ _FakeDeltaTable.file_count = 1
+
+ def _schema(self) -> ExternalDataSchema:
+ schema = ExternalDataSchema(id=_SCHEMA_ID, team_id=1, name="orders")
+ schema.source = ExternalDataSource(source_type="Postgres")
+ schema.table = None
+ return schema
+
+ def test_pinned_version_is_resolved_once_across_repeated_calls(self) -> None:
+ schema = self._schema()
+
+ with patch("deltalake.DeltaTable", _FakeDeltaTable):
+ first = backfill_snapshot.resolve_snapshot_plan(schema, version=5)
+ second = backfill_snapshot.resolve_snapshot_plan(schema, version=5)
+
+ assert _FakeDeltaTable.instances == 1
+ assert first == second
+
+ def test_different_pinned_versions_are_each_resolved(self) -> None:
+ schema = self._schema()
+
+ with patch("deltalake.DeltaTable", _FakeDeltaTable):
+ backfill_snapshot.resolve_snapshot_plan(schema, version=5)
+ backfill_snapshot.resolve_snapshot_plan(schema, version=6)
+
+ assert _FakeDeltaTable.instances == 2
+
+ def test_unpinned_head_version_is_never_cached(self) -> None:
+ schema = self._schema()
+
+ with patch("deltalake.DeltaTable", _FakeDeltaTable):
+ backfill_snapshot.resolve_snapshot_plan(schema)
+ backfill_snapshot.resolve_snapshot_plan(schema)
+
+ assert _FakeDeltaTable.instances == 2
+
+ def test_plan_exceeding_weight_budget_is_never_cached(self) -> None:
+ # A single table's plan can carry an unbounded number of files/commit
+ # keys — a table big enough to exceed the whole cache's budget on its
+ # own must not be retained at all, or one tenant's giant table could
+ # make the cache hold an unbounded amount indefinitely.
+ with patch.object(backfill_snapshot, "_PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT", 10):
+ _FakeDeltaTable.file_count = 11
+ schema = self._schema()
+
+ with patch("deltalake.DeltaTable", _FakeDeltaTable):
+ backfill_snapshot.resolve_snapshot_plan(schema, version=5)
+ backfill_snapshot.resolve_snapshot_plan(schema, version=5)
+
+ assert _FakeDeltaTable.instances == 2
+ assert len(backfill_snapshot._pinned_snapshot_plan_cache) == 0
+
+ def test_cache_evicts_oldest_entry_once_weight_budget_exceeded(self) -> None:
+ with patch.object(backfill_snapshot, "_PINNED_SNAPSHOT_PLAN_CACHE_MAX_WEIGHT", 10):
+ _FakeDeltaTable.file_count = 6
+ schema = self._schema()
+
+ with patch("deltalake.DeltaTable", _FakeDeltaTable):
+ backfill_snapshot.resolve_snapshot_plan(schema, version=1) # weight 6, fits
+ backfill_snapshot.resolve_snapshot_plan(schema, version=2) # weight 6: evicts v1 (6+6 > 10)
+ assert _FakeDeltaTable.instances == 2
+
+ backfill_snapshot.resolve_snapshot_plan(schema, version=1) # re-reads: was evicted
+ assert _FakeDeltaTable.instances == 3