: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
perf(data-warehouse): reuse the duckgres session across a group's live batches (#73028)
Eric Duong7f1be2c50bb7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.pyindex f8bcfd5419a9..8d6b89717f19 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py@@ -1,9 +1,12 @@from __future__ import annotationsimport time+import atexit+import threadingfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom dataclasses import dataclass+from time import sleep as _real_sleep # captured before any test patches this module's `time`from typing import Any, Literalfrom django.conf import settings@@ -92,6 +95,129 @@ class BatchApplyOperation:primary_keys: list[str] | None = None+class _DuckgresSessionCache:+ """Reuse one duckgres connection across consecutive live batches of a group.++ The dominant per-batch costs measured in prod (2026-07-22) are per-SESSION+ fixed costs, not row volume: worker session create (~0.5-1s), the extended-+ protocol describe probe's cold catalog enumeration (~5-19s), and the+ transaction's first-write metadata touch on the target table (~12-19s).+ All are warm on a reused session, taking a live batch from ~30-40s to ~2s.++ Keyed by (org_id, team_id, schema_id): the sink's group lease serializes+ each (team, schema) to one pod task at a time, so entries are never used+ concurrently — the lock guards only the dict. The org is part of the key+ so a team transferred between organizations can never keep writing through+ the previous org's authenticated connection. Entries are dropped on any+ processing error (the connection may hold aborted-transaction state), after+ IDLE_TTL without reuse, and past MAX_AGE outright (the extract-read secret+ embeds session credentials that expire; a fresh session re-mints them).+ A daemon sweeper enforces both bounds independently of traffic — without+ it, a drained group's session would pin its duckgres worker (one session+ per worker) indefinitely, outside the sink's org connection budget; with+ it, the pin is bounded by IDLE_TTL + SWEEP_INTERVAL. atexit clears the+ cache on graceful shutdown.+ """++ IDLE_TTL_SECONDS = 90.0+ MAX_AGE_SECONDS = 600.0+ SWEEP_INTERVAL_SECONDS = 30.0+ # Retained sessions pin duckgres workers, so cap them per org: even a burst+ # of sequentially drained groups can never hold more than this many of an+ # org's connections beyond its active leases (per consumer pod).+ MAX_SESSIONS_PER_ORG = 4++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._entries: dict[tuple[str, int, str], tuple[psycopg.Connection[Any], float, float]] = {}+ self._sweeper_started = False++ def acquire(self, org_id: str, team_id: int, schema_id: str) -> tuple[psycopg.Connection[Any] | None, float]:+ """Return (connection, session_created_at); (None, now) means connect fresh.++ created_at is threaded back through store() so the MAX_AGE credential+ cap tracks the ORIGINAL session creation across any number of reuses.+ """+ key = (org_id, team_id, schema_id)+ now = time.monotonic()+ with self._lock:+ entry = self._entries.pop(key, None)+ if entry is None:+ return None, now+ conn, created_at, last_used = entry+ if now - last_used > self.IDLE_TTL_SECONDS or now - created_at > self.MAX_AGE_SECONDS:+ self._close_quietly(conn)+ return None, now+ return conn, created_at++ def store(+ self, org_id: str, team_id: int, schema_id: str, conn: psycopg.Connection[Any], created_at: float+ ) -> None:+ self._ensure_sweeper()+ key = (org_id, team_id, schema_id)+ overflow = []+ with self._lock:+ previous = self._entries.get(key)+ self._entries[key] = (conn, created_at, time.monotonic())+ org_keys = [k for k in self._entries if k[0] == org_id]+ if len(org_keys) > self.MAX_SESSIONS_PER_ORG:+ org_keys.sort(key=lambda k: self._entries[k][2]) # oldest last-use first+ for stale_key in org_keys[: len(org_keys) - self.MAX_SESSIONS_PER_ORG]:+ overflow.append(self._entries.pop(stale_key))+ if previous is not None and previous[0] is not conn:+ self._close_quietly(previous[0])+ for other_conn, _, _ in overflow:+ self._close_quietly(other_conn)++ def _ensure_sweeper(self) -> None:+ # Lazy start: this module is imported by processes that never run the+ # sink; only a process that actually caches a session gets the thread.+ with self._lock:+ if self._sweeper_started:+ return+ self._sweeper_started = True+ threading.Thread(target=self._sweep_loop, daemon=True, name="duckgres-session-cache-sweeper").start()++ def _sweep_loop(self) -> None:+ while True:+ _real_sleep(self.SWEEP_INTERVAL_SECONDS)+ try:+ self._evict_stale()+ except Exception:+ pass++ def _evict_stale(self) -> None:+ """Close entries past either bound — runs on the sweeper, not on traffic."""+ now = time.monotonic()+ with self._lock:+ stale = [+ k+ for k, (_, created_at, used) in self._entries.items()+ if now - used > self.IDLE_TTL_SECONDS or now - created_at > self.MAX_AGE_SECONDS+ ]+ evicted = [self._entries.pop(k) for k in stale]+ for conn, _, _ in evicted:+ self._close_quietly(conn)++ def clear(self) -> None:+ with self._lock:+ entries = list(self._entries.values())+ self._entries.clear()+ for conn, _, _ in entries:+ self._close_quietly(conn)++ @staticmethod+ def _close_quietly(conn: psycopg.Connection[Any]) -> None:+ try:+ conn.close()+ except Exception:+ pass+++_session_cache = _DuckgresSessionCache()+atexit.register(_session_cache.clear)++def process_batch(batch: PendingBatch) -> None:# Threads are reused across batches; drop stale app-DB connections so the ORM# reads below reconnect instead of failing every attempt after a DB bounce.@@ -115,45 +241,77 @@ def process_batch(batch: PendingBatch) -> None:schema = job.schemakind = "backfill" if _is_backfill_batch(batch) else "live"+ # One ORM lookup serves both the cache key and the connection config; it is+ # per-batch on purpose so the key always reflects the team's CURRENT org.+ org_id = str(Team.objects.only("organization_id").get(id=batch.team_id).organization_id)timings: dict[str, float] = {}- # Fresh connect + session + secret is per-batch fixed cost; measured as one- # phase so the connection-reuse trade-off is visible against the apply itself.- # Recorded in a finally so a slow/failing connect (e.g. cold-tenant activation- # timeout) still lands in the phase metric, matching the _timed error-path capture.+ # Connect + session + secret is a fixed cost; measured as one phase so the+ # connection-reuse win is visible against the apply itself (a cache hit+ # records ~0). Recorded in a finally so a slow/failing connect (e.g.+ # cold-tenant activation timeout) still lands in the phase metric.connect_start = time.monotonic()- try:- with _connect_to_duckgres(batch.team_id) as conn:- # The sink only reads parquet over S3; httpfs is bundled in the duckgres- # worker image so INSTALL is a local no-op. Do NOT add extensions that are- # not bundled (e.g. delta): egress-restricted workers silently drop the- # CDN download and the statement hangs.- setup_duckgres_session(conn, extensions=("httpfs",))- _create_extract_read_secret(conn)- _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)- try:- if kind == "backfill":+ if kind == "backfill":+ # Backfills are rare, long, and chunk-coalesced already — keep the+ # simple fresh-connection lifecycle.+ try:+ with _connect_to_duckgres(org_id) as conn:+ # The sink only reads parquet over S3; httpfs is bundled in the duckgres+ # worker image so INSTALL is a local no-op. Do NOT add extensions that are+ # not bundled (e.g. delta): egress-restricted workers silently drop the+ # CDN download and the statement hangs.+ setup_duckgres_session(conn, extensions=("httpfs",))+ _create_extract_read_secret(conn)+ _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)+ try:_process_backfill_batch(conn, batch, schema, timings=timings)- else:- _process_batch(conn, batch, schema, timings=timings)- except DuckgresBatchAlreadyAppliedError:- # A concurrent processor (lost advisory-lock session + recovery sweep)- # won the marker insert; its committed write is the canonical one and- # ours rolled back. Treat as applied.- logger.info(- "duckgres_batch_applied_by_concurrent_processor",- team_id=batch.team_id,- schema_id=batch.schema_id,- run_uuid=batch.run_uuid,- batch_index=batch.batch_index,- )+ except DuckgresBatchAlreadyAppliedError:+ _log_applied_by_concurrent_processor(batch)+ finally:+ if "connect_setup" not in timings:+ _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)+ return++ # Distinct name from the backfill branch's `with ... as conn` binding: this+ # one is Optional until the cache miss connects, and mypy types by first use.+ session_conn, session_created_at = _session_cache.acquire(org_id, batch.team_id, batch.schema_id)+ try:+ if session_conn is None:+ session_conn = _connect_to_duckgres(org_id)+ setup_duckgres_session(session_conn, extensions=("httpfs",))+ _create_extract_read_secret(session_conn)+ _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)+ try:+ _process_batch(session_conn, batch, schema, timings=timings)+ except DuckgresBatchAlreadyAppliedError:+ _log_applied_by_concurrent_processor(batch)+ except BaseException:+ # The connection may hold aborted-transaction or half-streamed state;+ # never cache it. The queue's retry gets a fresh session.+ if session_conn is not None:+ _DuckgresSessionCache._close_quietly(session_conn)+ raise+ else:+ _session_cache.store(org_id, batch.team_id, batch.schema_id, session_conn, created_at=session_created_at)finally:if "connect_setup" not in timings:_record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)-def _connect_to_duckgres(team_id: int) -> psycopg.Connection[Any]:- team = Team.objects.only("organization_id").get(id=team_id)- config = get_duckgres_config_for_org(str(team.organization_id))+def _log_applied_by_concurrent_processor(batch: PendingBatch) -> None:+ # A concurrent processor (lost advisory-lock session + recovery sweep)+ # won the marker insert; its committed write is the canonical one and+ # ours rolled back. Treat as applied.+ logger.info(+ "duckgres_batch_applied_by_concurrent_processor",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ run_uuid=batch.run_uuid,+ batch_index=batch.batch_index,+ )+++def _connect_to_duckgres(org_id: str) -> psycopg.Connection[Any]:+ config = get_duckgres_config_for_org(org_id)return psycopg.connect(host=config["DUCKGRES_HOST"],port=config["DUCKGRES_PORT"],diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.pyindex 425502c6a728..7918dd55107d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py@@ -10,6 +10,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_mark_duckgres_batch_applied,_process_backfill_batch,_process_batch,+ _session_cache,+ process_batch,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (PendingBatch,@@ -555,3 +557,176 @@ class TestBackfillProcessing:_process_backfill_batch(conn, batch, _make_schema())insert.assert_not_called()+++class TestLiveSessionReuse:+ """Reusing the duckgres session across a group's live batches removes the+ dominant per-batch fixed costs measured in prod on 2026-07-22: worker+ session create, the describe probe's cold catalog enumeration, and the+ first-write metadata touch (~20-40s combined per batch)."""++ @pytest.fixture(autouse=True)+ def _reset_cache_and_orm(self):+ _session_cache.clear()+ patches = [+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.close_old_connections"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.ExternalDataJob"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.Team"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._process_batch"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.setup_duckgres_session"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._create_extract_read_secret"+ ),+ ]+ self.mocks = [p.start() for p in patches]+ (_, self.mock_job, self.mock_team, self.mock_inner, self.mock_setup, self.mock_secret) = self.mocks+ self.mock_team.objects.only.return_value.get.return_value.organization_id = "org-a"+ yield+ for p in patches:+ p.stop()+ _session_cache.clear()++ def _connect_patch(self):+ return patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._connect_to_duckgres"+ )++ def test_consecutive_live_batches_reuse_one_connection_and_preamble(self):+ with self._connect_patch() as mock_connect:+ mock_connect.return_value = MagicMock()+ process_batch(_make_batch(batch_index=1))+ process_batch(_make_batch(batch_index=2))++ assert mock_connect.call_count == 1+ assert self.mock_setup.call_count == 1+ assert self.mock_secret.call_count == 1+ assert self.mock_inner.call_count == 2++ def test_groups_get_separate_connections(self):+ with self._connect_patch() as mock_connect:+ mock_connect.side_effect = [MagicMock(), MagicMock()]+ process_batch(_make_batch(schema_id="schema-1"))+ process_batch(_make_batch(schema_id="schema-2"))++ assert mock_connect.call_count == 2++ def test_failed_apply_drops_the_cached_connection(self):+ conn1, conn2 = MagicMock(), MagicMock()+ self.mock_inner.side_effect = [RuntimeError("apply failed"), None]+ with self._connect_patch() as mock_connect:+ mock_connect.side_effect = [conn1, conn2]+ with pytest.raises(RuntimeError):+ process_batch(_make_batch(batch_index=1))+ process_batch(_make_batch(batch_index=2))++ conn1.close.assert_called_once()+ assert mock_connect.call_count == 2++ def test_expired_session_is_replaced(self, monkeypatch):+ conn1, conn2 = MagicMock(), MagicMock()+ clock = {"now": 1000.0}+ monkeypatch.setattr(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.time",+ MagicMock(monotonic=lambda: clock["now"]),+ )+ with self._connect_patch() as mock_connect:+ mock_connect.side_effect = [conn1, conn2]+ process_batch(_make_batch(batch_index=1))+ clock["now"] += 10_000 # far past both idle TTL and absolute age cap+ process_batch(_make_batch(batch_index=2))++ conn1.close.assert_called_once()+ assert mock_connect.call_count == 2++ def test_absolute_age_cap_survives_steady_reuse(self, monkeypatch):+ # The extract-read secret embeds expiring session credentials, so the+ # cap must track the ORIGINAL session creation, not the last reuse.+ conn1, conn2 = MagicMock(), MagicMock()+ clock = {"now": 1000.0}+ monkeypatch.setattr(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.time",+ MagicMock(monotonic=lambda: clock["now"]),+ )+ with self._connect_patch() as mock_connect:+ mock_connect.side_effect = [conn1, conn2]+ for i in range(12): # reuse every 61s: idle TTL never trips, age cap must+ process_batch(_make_batch(batch_index=i))+ clock["now"] += 61.0++ conn1.close.assert_called_once()+ assert mock_connect.call_count == 2++ def test_evict_stale_closes_idle_sessions_without_new_traffic(self, monkeypatch):+ # Review finding (Greptile P1 / hex-security): eviction must not depend+ # on a later acquire()/store() — a drained group's session would pin a+ # duckgres worker indefinitely. The sweeper calls _evict_stale on a+ # timer; this exercises it directly with a controlled clock.+ conn1 = MagicMock()+ clock = {"now": 1000.0}+ monkeypatch.setattr(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.time",+ MagicMock(monotonic=lambda: clock["now"]),+ )+ with self._connect_patch() as mock_connect:+ mock_connect.return_value = conn1+ process_batch(_make_batch(batch_index=1))++ clock["now"] += 91.0+ _session_cache._evict_stale()++ conn1.close.assert_called_once()++ def test_store_starts_the_sweeper_thread_once(self):+ with self._connect_patch() as mock_connect:+ mock_connect.return_value = MagicMock()+ process_batch(_make_batch(batch_index=1))+ process_batch(_make_batch(batch_index=2))++ assert _session_cache._sweeper_started is True++ def test_org_change_invalidates_the_cached_session(self):+ # Review finding (veria): the cache key must include the org so a team+ # transferred between organizations can never keep writing through the+ # previous org's authenticated connection.+ conn1, conn2 = MagicMock(), MagicMock()+ with self._connect_patch() as mock_connect:+ mock_connect.side_effect = [conn1, conn2]+ process_batch(_make_batch(batch_index=1))+ self.mock_team.objects.only.return_value.get.return_value.organization_id = "org-b"+ process_batch(_make_batch(batch_index=2))++ assert mock_connect.call_count == 2++ def test_per_org_session_cap_evicts_the_oldest_entry(self):+ # hex-security follow-up: retained sessions must never accumulate past+ # a small per-org bound, even across many sequentially drained groups —+ # each cached session pins a duckgres worker.+ conns = [MagicMock() for _ in range(5)]+ with self._connect_patch() as mock_connect:+ mock_connect.side_effect = conns+ for i in range(5):+ process_batch(_make_batch(schema_id=f"schema-{i}"))++ assert len(_session_cache._entries) == 4+ conns[0].close.assert_called_once()+ for c in conns[1:]:+ c.close.assert_not_called()++ def test_cache_miss_resolves_the_team_once(self):+ # greptile follow-up: org resolution feeds both the cache key and the+ # connection config — one ORM lookup per batch, not two.+ with self._connect_patch() as mock_connect:+ mock_connect.return_value = MagicMock()+ process_batch(_make_batch(batch_index=1))++ assert self.mock_team.objects.only.return_value.get.call_count == 1