: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
Revert "fix(ducklings): make duckgres backfill survive worker churn; stop hogging giant workers" (#63403)
James Greenhill4239a0e4c01e
diff --git a/.dockerignore b/.dockerignoreindex 5430e46c0414..aa50fc754719 100644--- a/.dockerignore+++ b/.dockerignore@@ -103,10 +103,6 @@ products/**/*_test.pyproducts/**/*.test.*products/**/*.spec.*products/**/*.stories.*-posthog/**/test_*.py-posthog/**/*_test.py-ee/**/test_*.py-ee/**/*_test.pyfrontend/src/**/*.test.*frontend/src/**/*.spec.*frontend/src/**/*.stories.*diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 97ba0aa29f20..00086ebf6250 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -32,9 +32,7 @@ Partition Strategy:import osimport json-import timeimport calendar-from collections.abc import Callablefrom datetime import date, datetime, timedeltafrom typing import Any@@ -82,94 +80,57 @@ logger = structlog.get_logger(__name__)# so the DAG can hardcode it everywhere instead of threading a config value.DUCKLAKE_ALIAS = "ducklake"-# Catalog alias duckgres uses when an org has the Iceberg (Lakekeeper) backend-# enabled — see duckgres server/iceberg/migration.go CatalogName. Attached only-# when Iceberg is enabled for the org's warehouse, so all Iceberg work here is-# best-effort: failures are logged and never abort the DuckLake backfill.-ICEBERG_ALIAS = "iceberg"--# Teams that additionally dual-write their backfill into Iceberg alongside-# DuckLake. Hardcoded allowlist for dogfooding the Iceberg path; DuckLake-# remains the source of truth for every team, including these.-ICEBERG_BACKFILL_TEAM_IDS = {2}---def iceberg_enabled_for_team(team_id: int) -> bool:- """Whether this team should dual-write its backfill into Iceberg."""- return team_id in ICEBERG_BACKFILL_TEAM_IDS---# Duckgres connect timeout bounds the TCP+TLS handshake only. A backfill-# connection may have to wait for duckgres to spin up a fresh worker (a cold-# worker can require provisioning a new node, which takes minutes), so the-# handshake budget is generous and `_connect_duckgres` retries with backoff.+# Duckgres connection timeouts: connect_timeout bounds the TCP+TLS handshake;+# statement_timeout bounds query execution to prevent hung Dagster workers.+# A backfill connection may have to wait for duckgres to spin up a fresh worker+# (a cold worker can require provisioning a new node, which takes minutes), so+# the handshake budget is generous and `_connect_duckgres` retries with backoff.# Must exceed the binding duckgres server-side wait, which is the OUTER# workerQueueTimeout (5m) — not warmAcquireTimeout (4m). On a warm-pool miss the# CP blocks the connect server-side waiting for a colocated worker (which may need# a cold node) instead of bouncing us with "no warm worker available"; that whole# block is bounded by workerQueueTimeout. 360s gives margin over the 300s server# block + TLS/handshake. Ladder: warmAcquire 4m < workerQueueTimeout 5m < 360s.-#-# We deliberately set NO statement_timeout. Duckling backfills are long-running-# OLAP statements (a partition DELETE / file registration over an event-day) —-# running long is the whole point of an OLAP engine, so capping them at 5 minutes-# (or any value) is wrong. A worker that disappears mid-statement is handled by-# reconnect-and-retry (`_DuckgresSession`), not by pre-emptively killing the query.DUCKGRES_CONNECT_TIMEOUT = 360 # seconds+DUCKGRES_STATEMENT_TIMEOUT_MS = 300_000 # 5 minutes-# Worker-profile control. When enabled, a backfill connection asks duckgres for a-# small COLOCATED (bin-packed) worker via libpq startup options, so it bursts into-# a right-sized pod instead of contending for the big exclusive shared workers-# (270GB / 46-thread). A metadata-only DuckLake register/DELETE has no use for-# that much worker, and grabbing one made the backfill both wasteful and fragile —-# a single shared worker dying mid-statement took out the partition. The server-# gate (DUCKGRES_K8S_ALLOW_CLIENT_WORKER_PROFILE) is on in prod, so this defaults-# ON; set DUCKGRES_WORKER_PROFILE_ENABLED=0 to put a deployment back on the big-# exclusive workers.+# Worker-profile opt-in. When enabled, a backfill connection asks duckgres for a+# small COLOCATED (bin-packed) worker via libpq startup options, so it bursts+# into a ready pod instead of contending for the big exclusive shared workers+# (the cause of the backfill ConnectionTimeouts). Gated so it stays off until+# duckgres has the colocated warm pool deployed and the server gate is on.## Evaluated once at process startup, not per connection/partition — toggling it# (including rollback) requires redeploying the Dagster code location so the# process restarts and re-reads the env, not just unsetting the variable.-DUCKGRES_WORKER_PROFILE_ENABLED = os.environ.get("DUCKGRES_WORKER_PROFILE_ENABLED", "true").strip().lower() in (+DUCKGRES_WORKER_PROFILE_ENABLED = os.environ.get("DUCKGRES_WORKER_PROFILE_ENABLED", "").strip().lower() in ("1","true","yes","on",)-# Colocated worker sizes. Iceberg-allowlisted orgs dual-write via an-# INSERT ... SELECT read_parquet over a full event-day (memory-heavy), so they-# get a larger colocated pod than the metadata-only DuckLake register path.+# Colocated worker size for the metadata-only DuckLake register path.DUCKGRES_BACKFILL_COLOCATE_CPU = "4"DUCKGRES_BACKFILL_COLOCATE_MEMORY = "16Gi"-DUCKGRES_ICEBERG_BACKFILL_COLOCATE_CPU = "8"-DUCKGRES_ICEBERG_BACKFILL_COLOCATE_MEMORY = "48Gi"-def _duckgres_backfill_options(team_id: int) -> str:+def _duckgres_backfill_options() -> str:"""libpq startup `options` for a backfill connection.- When the worker-profile feature is enabled (the default), requests a small- colocated worker shape (larger for Iceberg-allowlisted orgs, which dual-write- via a memory-heavier `INSERT ... SELECT read_parquet`). Returns a single- space-joined `-c key=value` string — psycopg forwards it as the startup- `options` parameter, which duckgres parses to size/schedule the worker. No- statement_timeout is set (see DUCKGRES_CONNECT_TIMEOUT note above). Returns ""- when the profile is disabled, so the connection falls back to the default- exclusive worker with no extra startup options.+ Always bounds statement execution; when the worker-profile feature is+ enabled, additionally requests a small colocated worker shape. Returns a+ single space-joined `-c key=value` string — psycopg forwards it as the+ startup `options` parameter, which duckgres parses to size/schedule the+ worker."""- if not DUCKGRES_WORKER_PROFILE_ENABLED:- return ""- if iceberg_enabled_for_team(team_id):- cpu, memory = DUCKGRES_ICEBERG_BACKFILL_COLOCATE_CPU, DUCKGRES_ICEBERG_BACKFILL_COLOCATE_MEMORY- else:- cpu, memory = DUCKGRES_BACKFILL_COLOCATE_CPU, DUCKGRES_BACKFILL_COLOCATE_MEMORY- return " ".join(- [+ opts = [f"-c statement_timeout={DUCKGRES_STATEMENT_TIMEOUT_MS}"]+ if DUCKGRES_WORKER_PROFILE_ENABLED:+ opts += ["-c duckgres.colocate=true",- f"-c duckgres.worker_cpu={cpu}",- f"-c duckgres.worker_memory={memory}",+ f"-c duckgres.worker_cpu={DUCKGRES_BACKFILL_COLOCATE_CPU}",+ f"-c duckgres.worker_memory={DUCKGRES_BACKFILL_COLOCATE_MEMORY}",]- )+ return " ".join(opts)@retry(@@ -196,8 +157,7 @@ def _get_cluster() -> ClickhouseCluster:# or the CP giving up after its block): the delay cap must exceed one full# attempt so a second one can actually run, hence 780s (~2 attempts) rather# than 360s (which a single 360s attempt would exhaust, making retries a no-op).- # This guards only the initial connect; a worker that drops mid-statement is- # handled separately by _DuckgresSession's reconnect-and-retry.+ # statement_timeout (set per connection) is separate.stop=stop_after_delay(780) | stop_after_attempt(12),wait=wait_exponential(multiplier=1, min=5, max=60),retry=retry_if_exception_type((psycopg.OperationalError, OSError)),@@ -232,134 +192,10 @@ def _connect_duckgres(catalog: DuckLakeCatalog) -> psycopg.Connection[Any]:conninfo,autocommit=True,connect_timeout=DUCKGRES_CONNECT_TIMEOUT,- options=_duckgres_backfill_options(catalog.team_id),+ options=_duckgres_backfill_options(),)-_CONNECTION_DROPPED_SQLSTATES = {- "57P01", # admin_shutdown- "57P02", # crash_shutdown- "57P03", # cannot_connect_now-}--_CONNECTION_DROPPED_MARKERS = (- "broken pipe",- "code = unavailable",- "code=unavailable",- "connection refused",- "connection reset",- "connection to server was closed",- "connection to server was lost",- "consuming input failed",- "eof detected",- "error reading from server",- "flight execute",- "server closed the connection",- "terminating connection due to administrator command",- "transport:",-)---def _connection_dropped(exc: BaseException) -> bool:- """True when `exc` means the duckgres worker/connection went away mid-statement- (worker pod died, control plane lost the Flight stream), as opposed to a- SQL/logic error. Recoverable by reconnecting to a fresh worker and replaying- the (idempotent, transactional) duckgres metadata op.- """- msg = str(exc).lower()- if isinstance(exc, psycopg.errors.ConnectionException):- return True-- sqlstate = getattr(exc, "sqlstate", None)- if isinstance(sqlstate, str) and (sqlstate.startswith("08") or sqlstate in _CONNECTION_DROPPED_SQLSTATES):- return True-- # psycopg.OperationalError also covers permanent operational failures (for- # example SQLSTATE class 53 resource exhaustion), so only retry the message- # shapes that are clearly connection/transport loss.- if isinstance(exc, psycopg.OperationalError):- return any(marker in msg for marker in _CONNECTION_DROPPED_MARKERS)-- # The control plane surfaces a worker-side Flight RPC failure — e.g. the- # worker pod dying mid-DELETE — back through the PG wire as InternalError- # wrapping transport-specific gRPC text ("code = Unavailable", "connection- # reset by peer", "transport: ...", "error reading from server").- if isinstance(exc, psycopg.InternalError):- return any(marker in msg for marker in _CONNECTION_DROPPED_MARKERS)- return False---class _DuckgresSession:- """A duckgres connection that transparently reconnects to a fresh worker when- the current worker drops mid-statement.-- Duckling backfill duckgres ops (partition DELETE, file registration, table- DDL) are idempotent and transactional, so replaying one on a new worker after- a mid-statement worker death is safe: an uncommitted DuckLake transaction- leaves no trace, and re-running a day's DELETE/register reproduces the same- state. A worker pod can disappear under a long-running statement for many- reasons (node consolidation, a control-plane rollout, an engine crash); the- backfill should survive that by re-acquiring a worker, not fail the whole- partition on the first blip.- """-- MAX_ATTEMPTS = 4-- def __init__(self, context: AssetExecutionContext, catalog: DuckLakeCatalog) -> None:- self._context = context- self._catalog = catalog- self._conn = _connect_duckgres(catalog)-- @property- def conn(self) -> psycopg.Connection[Any]:- return self._conn-- def run(self, what: str, op: Callable[[psycopg.Connection[Any]], Any]) -> Any:- """Run `op(conn)`, reconnecting to a fresh worker and retrying if the- worker/connection drops mid-statement. Non-connection errors propagate- immediately (no retry); the last connection error is re-raised once the- attempt budget is exhausted.- """- last_exc: Exception | None = None- for attempt in range(1, self.MAX_ATTEMPTS + 1):- try:- return op(self._conn)- except Exception as exc:- if not _connection_dropped(exc):- raise- last_exc = exc- if attempt == self.MAX_ATTEMPTS:- break- self._context.log.warning(- f"duckgres worker/connection dropped during {what} "- f"(attempt {attempt}/{self.MAX_ATTEMPTS}); reconnecting to a fresh worker: {exc}"- )- logger.warning(- "duckling_duckgres_reconnect",- what=what,- attempt=attempt,- error=str(exc),- error_type=type(exc).__name__,- )- self._reconnect()- time.sleep(min(2**attempt, 30))- assert last_exc is not None # only reached after a connection-drop break- raise last_exc-- def _reconnect(self) -> None:- try:- self._conn.close()- except Exception:- pass- self._conn = _connect_duckgres(self._catalog)-- def close(self) -> None:- try:- self._conn.close()- except Exception:- pass--# Columns to export from ClickHouse events table for duckling backfill.# ClickHouse exports DateTime64 as TIMESTAMP WITH TIME ZONE in Parquet.# DuckLake table uses TIMESTAMPTZ to match this format.@@ -447,35 +283,6 @@ EXPECTED_DUCKLAKE_PERSONS_COLUMNS = {"_inserted_at",}-# Iceberg has no unsigned integer types, so the persons table mirrors-# PERSONS_TABLE_DDL but stores person_version as BIGINT instead of UBIGINT.-# The UInt64 values exported from ClickHouse fit comfortably in a signed-# 64-bit column in practice (versions are small monotonic counters).-ICEBERG_PERSONS_TABLE_DDL = """-CREATE TABLE IF NOT EXISTS {catalog}.posthog.persons (- team_id BIGINT,- distinct_id VARCHAR,- id VARCHAR,- properties VARCHAR,- created_at TIMESTAMPTZ,- is_identified BOOLEAN,- person_distinct_id_version BIGINT,- person_version BIGINT,- _timestamp TIMESTAMPTZ,- _inserted_at TIMESTAMPTZ-)-"""--# Iceberg partition specs. Each uses a SINGLE Iceberg temporal transform per-# source column — NOT the multi-level year/month/day spec the DuckLake tables-# use. Lakekeeper rejects declaring several temporal transforms on one source-# column as redundant ("Cannot add redundant partition with source id … and-# transform `time`"), and a single day()/month() transform already encodes the-# full date for partition pruning. DuckDB's Iceberg INSERT path supports these-# transforms as of 1.5.3 (verified against the live Lakekeeper catalog).-ICEBERG_EVENTS_PARTITION_EXPR = "day(timestamp)"-ICEBERG_PERSONS_PARTITION_EXPR = "month(_timestamp)"-duckling_events_partitions_def = DynamicPartitionsDefinition(name="duckling_events_backfill")duckling_persons_partitions_def = DynamicPartitionsDefinition(name="duckling_persons_backfill")@@ -1253,9 +1060,6 @@ def register_file_with_duckling(DuckLake transaction conflicts are retried server-side by duckgres. Connectionretries live in the caller — this helper operates on a connection it doesn't own.- The caller may replay this call after losing the client connection before it- sees the server result; DuckLake file registration must therefore remain- idempotent for a duplicate file path within the same table.Args:context: Dagster asset execution context.@@ -1460,9 +1264,6 @@ def register_persons_file_with_duckling(DuckLake transaction conflicts are retried server-side by duckgres. Connectionretries live in the caller — this helper operates on a connection it doesn't own.- The caller may replay this call after losing the client connection before it- sees the server result; DuckLake file registration must therefore remain- idempotent for a duplicate file path within the same table."""if config.skip_ducklake_registration:context.log.info("Skipping DuckLake registration (skip_ducklake_registration=True)")@@ -1500,222 +1301,6 @@ def register_persons_file_with_duckling(return True-def drop_iceberg_table(- context: AssetExecutionContext,- conn: psycopg.Connection[Any],- table: str,-) -> None:- """Best-effort DROP of the Iceberg table, mirroring delete_tables for DuckLake.-- Used when config.delete_tables wipes the DuckLake table so the Iceberg copy- is reset to match instead of having dual-write append on top of stale rows.- Failures are logged and swallowed — the Iceberg path must never abort the- DuckLake backfill (e.g. when the catalog isn't attached for this org).- """- _validate_identifier(table)- try:- conn.execute(f"DROP TABLE IF EXISTS {ICEBERG_ALIAS}.posthog.{table}")- context.log.info(f"Dropped Iceberg table {ICEBERG_ALIAS}.posthog.{table} (delete_tables=True)")- except Exception as exc:- context.log.warning(f"Best-effort Iceberg DROP of {table} failed (continuing): {exc}")- logger.warning(- "duckling_iceberg_drop_table_failed",- table=table,- error=str(exc),- error_type=type(exc).__name__,- )---def _set_iceberg_table_partitioning(- context: AssetExecutionContext,- conn: psycopg.Connection[Any],- table: str,- partition_expr: str,-) -> None:- """Best-effort partition-evolve an existing Iceberg table.-- `CREATE TABLE IF NOT EXISTS ... PARTITIONED BY` only partitions a *fresh*- table; a table created unpartitioned by an earlier deploy keeps its old- spec. `ALTER TABLE ... SET PARTITIONED BY` evolves it so new data files use- the new spec (existing files keep theirs — standard Iceberg partition- evolution). Lakekeeper rejects re-declaring the same spec as "redundant", so- that specific error is treated as success (the table is already partitioned- the way we want). Any other failure is logged and swallowed — partitioning- must never abort the best-effort dual-write.- """- _validate_identifier(table)- try:- conn.execute(f"ALTER TABLE {ICEBERG_ALIAS}.posthog.{table} SET PARTITIONED BY ({partition_expr})")- except Exception as exc:- # Lakekeeper rejects re-declaring an identical spec as redundant; that- # means the table already carries the partitioning we want.- if "redundant" in str(exc).lower():- return- context.log.warning(f"Best-effort Iceberg partition-evolve of {table} failed (continuing): {exc}")- logger.warning(- "duckling_iceberg_set_partitioning_failed",- table=table,- partition_expr=partition_expr,- error=str(exc),- error_type=type(exc).__name__,- )---def ensure_iceberg_table_exists(- context: AssetExecutionContext,- conn: psycopg.Connection[Any],- table: str,- ddl: str,- team_id: int | None = None,- partition_expr: str | None = None,-) -> bool:- """Create the Iceberg schema + table for dual-write, if missing.-- Returns True if the Iceberg catalog is usable for this run, False if the- catalog isn't attached or table creation failed — in which case the caller- skips Iceberg writes for the run without failing the DuckLake backfill.-- The `iceberg` catalog is only attached when the org's warehouse has the- Iceberg backend enabled (see lakekeeper-iceberg-catalog runbook in duckgres).-- When `partition_expr` is set the table is partitioned by a single Iceberg- temporal transform (e.g. `day(timestamp)`), and existing unpartitioned- tables are evolved in place via ALTER. DuckDB's Iceberg INSERT path supports- these transforms as of 1.5.3 (verified against the live Lakekeeper catalog).- A single transform per source column is used deliberately — Lakekeeper- rejects the multi-level `year/month/day` spec DuckLake uses as redundant, and- `day()`/`month()` already encode the full date for partition pruning.- """- _validate_identifier(table)- try:- conn.execute(f"CREATE SCHEMA IF NOT EXISTS {ICEBERG_ALIAS}.posthog")- create_sql = ddl.format(catalog=ICEBERG_ALIAS)- if partition_expr:- # Append the partition clause to the column-list DDL. Partitions a- # fresh table; a no-op if the table already exists (handled by the- # ALTER below).- create_sql = f"{create_sql.rstrip().rstrip(';')}\nPARTITIONED BY ({partition_expr})"- conn.execute(create_sql)- if partition_expr:- _set_iceberg_table_partitioning(context, conn, table, partition_expr)- return True- except Exception as exc:- context.log.warning(- f"Iceberg dual-write disabled for this run (team_id={team_id}) — could not ensure "- f"{ICEBERG_ALIAS}.posthog.{table}: {exc}. Is the Iceberg backend enabled for this org's warehouse?"- )- logger.warning(- "duckling_iceberg_ensure_table_failed",- table=table,- team_id=team_id,- error=str(exc),- error_type=type(exc).__name__,- )- return False---def write_partition_to_iceberg(- context: AssetExecutionContext,- conn: psycopg.Connection[Any],- table: str,- s3_path: str,- team_id: int,- timestamp_column: str,- partition_date: datetime | None,-) -> bool:- """Dual-write one exported Parquet file into the team's Iceberg table.-- Iceberg has no `ducklake_add_data_files` equivalent — the only write path is- `INSERT ... SELECT`, so the duckgres worker re-reads the Parquet from S3 and- writes Iceberg data + metadata itself. `BY NAME` matches on column name so we- don't depend on column ordering.-- `hive_partitioning=false` is required: the S3 keys carry year=/month=/day=- (events) or year=/month= (persons) parts, and read_parquet would otherwise- synthesize those as columns. `BY NAME` then fails to map them into a table- that has no such columns ("does not have a column with name day"). The- real data columns already live in the Parquet (ClickHouse exports with- use_hive_partitioning=0).-- Idempotency is best-effort: we attempt a partition-scoped DELETE first, but- DuckDB's Iceberg extension may not support DELETE, so a failure there is- logged and the INSERT proceeds. Re-running a partition can therefore leave- duplicate rows in Iceberg. DuckLake (which does support DELETE) remains the- source of truth.-- For full persons exports (partition_date is None) the DELETE targets all of- the team's rows.-- Returns True if the INSERT succeeded, False otherwise (never raises — the- DuckLake backfill must not fail because of an Iceberg write).- """- _validate_identifier(table)- _validate_identifier(timestamp_column)-- # Best-effort partition cleanup for idempotent re-runs. Use psql.Identifier- # for the catalog/table/column the same way the INSERT below does, so the- # whole function composes SQL one way.- try:- if partition_date is None:- delete_sql = psql.SQL("DELETE FROM {}.posthog.{} WHERE team_id = {}").format(- psql.Identifier(ICEBERG_ALIAS),- psql.Identifier(table),- psql.Literal(team_id),- )- else:- date_str = partition_date.strftime("%Y-%m-%d")- next_date_str = (partition_date + timedelta(days=1)).strftime("%Y-%m-%d")- delete_sql = psql.SQL("DELETE FROM {}.posthog.{} WHERE team_id = {} AND {} >= {} AND {} < {}").format(- psql.Identifier(ICEBERG_ALIAS),- psql.Identifier(table),- psql.Literal(team_id),- psql.Identifier(timestamp_column),- psql.Literal(date_str),- psql.Identifier(timestamp_column),- psql.Literal(next_date_str),- )- conn.execute(delete_sql)- except Exception as exc:- context.log.warning(- f"Iceberg partition delete skipped for {table} team_id={team_id} "- f"(DELETE may be unsupported) — re-run may duplicate rows: {exc}"- )- logger.warning(- "duckling_iceberg_delete_skipped",- table=table,- team_id=team_id,- partition_date=partition_date.strftime("%Y-%m-%d") if partition_date else None,- error=str(exc),- error_type=type(exc).__name__,- )-- try:- conn.execute(- psql.SQL(- "INSERT INTO {}.posthog.{} BY NAME SELECT * FROM read_parquet({}, hive_partitioning=false)"- ).format(- psql.Identifier(ICEBERG_ALIAS),- psql.Identifier(table),- psql.Literal(s3_path),- )- )- except Exception as exc:- context.log.warning(f"Iceberg dual-write failed for {table} team_id={team_id} from {s3_path}: {exc}")- logger.warning(- "duckling_iceberg_write_failed",- table=table,- team_id=team_id,- s3_path=s3_path,- error=str(exc),- error_type=type(exc).__name__,- )- return False-- context.log.info(f"Iceberg dual-write succeeded for {table} team_id={team_id} from {s3_path}")- logger.info("duckling_iceberg_write_success", table=table, team_id=team_id, s3_path=s3_path)- return True--@asset(partitions_def=duckling_events_partitions_def,name="duckling_events_backfill",@@ -1764,18 +1349,14 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac# Open one duckgres connection for all metadata operations, but skip it# entirely when no duckgres-backed work will run (dry_run / skip_ducklake_registration).should_use_duckgres = not (config.dry_run or config.skip_ducklake_registration)- session = _DuckgresSession(context, catalog) if should_use_duckgres else None- iceberg_enabled = False+ conn: psycopg.Connection[Any] | None = _connect_duckgres(catalog) if should_use_duckgres else Nonetry:- if session is not None:+ if conn is not None:# Delete events table if requested (dangerous - loses all data)if config.delete_tables:context.log.warning("delete_tables=True: Deleting events table...")try:- session.run(- "drop events table",- lambda c: c.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.events"),- )+ conn.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.events")except Exception:context.log.exception(f"Failed to drop events table for team_id={team_id}")logger.exception(@@ -1784,34 +1365,16 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBacbucket=catalog.bucket,)raise- # Keep Iceberg in sync with the DuckLake wipe (best-effort)- if iceberg_enabled_for_team(team_id):- drop_iceberg_table(context, session.conn, "events")# Create events table if it doesn't existif config.create_tables_if_missing:context.log.info("Ensuring events table exists in duckling catalog...")- session.run("ensure events table", lambda c: ensure_events_table_exists(context, catalog, c))+ ensure_events_table_exists(context, catalog, conn)# Validate schema before starting exportif not config.skip_schema_validation:context.log.info("Validating duckling schema compatibility...")- session.run("validate events schema", lambda c: validate_duckling_schema(context, catalog, c))-- # Dual-write to Iceberg for allowlisted teams (best-effort, non-fatal)- if iceberg_enabled_for_team(team_id):- context.log.info(f"Iceberg dual-write enabled for team_id={team_id}; ensuring Iceberg events table...")- iceberg_enabled = session.run(- "ensure iceberg events table",- lambda c: ensure_iceberg_table_exists(- context,- c,- "events",- EVENTS_TABLE_DDL,- team_id=team_id,- partition_expr=ICEBERG_EVENTS_PARTITION_EXPR,- ),- )+ validate_duckling_schema(context, catalog, conn)# Prepare ClickHouse settingsmerged_settings = DEFAULT_CLICKHOUSE_SETTINGS.copy()@@ -1827,7 +1390,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac# Process each date in the partitiontotal_exported = 0total_registered = 0- total_iceberg = 0s3_paths: list[str] = []for partition_date in dates:@@ -1835,12 +1397,8 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBaccontext.log.info(f"Processing date {date_str}...")# Delete existing DuckLake data for this partition before re-processing- if session is not None and config.cleanup_existing_partition_data:-- def delete_events_partition(conn: psycopg.Connection[Any], date: datetime = partition_date) -> None:- delete_events_partition_data(context, catalog, team_id, date, conn=conn)-- session.run(f"delete events partition {date_str}", delete_events_partition)+ if conn is not None and config.cleanup_existing_partition_data:+ delete_events_partition_data(context, catalog, team_id, partition_date, conn=conn)def do_export(client: Client, date: datetime = partition_date) -> str | None:with tags_context(kind="dagster", dagster=tags):@@ -1865,21 +1423,8 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBacif s3_path:total_exported += 1s3_paths.append(s3_path)- if session is not None:-- def register_events_file(conn: psycopg.Connection[Any], path: str = s3_path) -> bool:- return register_file_with_duckling(context, catalog, path, config, conn)-- registered_events_file = session.run(f"register events file {date_str}", register_events_file)- else:- registered_events_file = False- if registered_events_file:+ if conn is not None and register_file_with_duckling(context, catalog, s3_path, config, conn):total_registered += 1- if iceberg_enabled and session is not None:- if write_partition_to_iceberg(- context, session.conn, "events", s3_path, team_id, "timestamp", partition_date- ):- total_iceberg += 1context.add_output_metadata({@@ -1888,7 +1433,6 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac"dates_processed": len(dates),"files_exported": total_exported,"files_registered": total_registered,- "files_iceberg_written": total_iceberg,"bucket": catalog.bucket,})@@ -1906,8 +1450,8 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBac)finally:- if session is not None:- session.close()+ if conn is not None:+ conn.close()@asset(@@ -1968,18 +1512,14 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa# Open one duckgres connection for all metadata operations, but skip it# entirely when no duckgres-backed work will run (dry_run / skip_ducklake_registration).should_use_duckgres = not (config.dry_run or config.skip_ducklake_registration)- session = _DuckgresSession(context, catalog) if should_use_duckgres else None- iceberg_enabled = False+ conn: psycopg.Connection[Any] | None = _connect_duckgres(catalog) if should_use_duckgres else Nonetry:- if session is not None:+ if conn is not None:# Delete persons table if requested (dangerous - loses all data)if config.delete_tables:context.log.warning("delete_tables=True: Deleting persons table...")try:- session.run(- "drop persons table",- lambda c: c.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.persons"),- )+ conn.execute(f"DROP TABLE IF EXISTS {DUCKLAKE_ALIAS}.posthog.persons")except Exception:context.log.exception(f"Failed to drop persons table for team_id={team_id}")logger.exception(@@ -1988,33 +1528,15 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBabucket=catalog.bucket,)raise- # Keep Iceberg in sync with the DuckLake wipe (best-effort)- if iceberg_enabled_for_team(team_id):- drop_iceberg_table(context, session.conn, "persons")# Create persons table if it doesn't existif config.create_tables_if_missing:context.log.info("Ensuring persons table exists in duckling catalog...")- session.run("ensure persons table", lambda c: ensure_persons_table_exists(context, catalog, c))+ ensure_persons_table_exists(context, catalog, conn)if not config.skip_schema_validation:context.log.info("Validating duckling persons schema compatibility...")- session.run("validate persons schema", lambda c: validate_duckling_persons_schema(context, catalog, c))-- # Dual-write to Iceberg for allowlisted teams (best-effort, non-fatal)- if iceberg_enabled_for_team(team_id):- context.log.info(f"Iceberg dual-write enabled for team_id={team_id}; ensuring Iceberg persons table...")- iceberg_enabled = session.run(- "ensure iceberg persons table",- lambda c: ensure_iceberg_table_exists(- context,- c,- "persons",- ICEBERG_PERSONS_TABLE_DDL,- team_id=team_id,- partition_expr=ICEBERG_PERSONS_PARTITION_EXPR,- ),- )+ validate_duckling_persons_schema(context, catalog, conn)merged_settings = DEFAULT_CLICKHOUSE_SETTINGS.copy()merged_settings.update(settings_with_log_comment(context))@@ -2031,11 +1553,8 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBacontext.log.info(f"Full export mode: exporting all persons for team_id={team_id}")# Delete all existing persons data for this team before full re-export- if session is not None and config.cleanup_existing_partition_data:- session.run(- "delete all persons",- lambda c: delete_persons_partition_data(context, catalog, team_id, partition_date=None, conn=c),- )+ if conn is not None and config.cleanup_existing_partition_data:+ delete_persons_partition_data(context, catalog, team_id, partition_date=None, conn=conn)def do_full_export(client: Client) -> str | None:with tags_context(kind="dagster", dagster=tags):@@ -2057,18 +1576,9 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBafiles_exported = 1 if s3_path else 0files_registered = 0- files_iceberg_written = 0- if s3_path and session is not None:-- def register_full_persons_file(conn: psycopg.Connection[Any], path: str = s3_path) -> bool:- return register_persons_file_with_duckling(context, catalog, path, config, conn)-- if session.run("register persons file (full)", register_full_persons_file):+ if s3_path and conn is not None:+ if register_persons_file_with_duckling(context, catalog, s3_path, config, conn):files_registered = 1- if iceberg_enabled and write_partition_to_iceberg(- context, session.conn, "persons", s3_path, team_id, "_timestamp", None- ):- files_iceberg_written = 1context.add_output_metadata({@@ -2077,7 +1587,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa"export_mode": "full","files_exported": files_exported,"files_registered": files_registered,- "files_iceberg_written": files_iceberg_written,"bucket": catalog.bucket,})@@ -2097,21 +1606,14 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa# DAILY EXPORT MODE - process each date in the partitiontotal_exported = 0total_registered = 0- total_iceberg = 0for partition_date in dates:date_str = partition_date.strftime("%Y-%m-%d")context.log.info(f"Processing persons for date {date_str}...")# Delete existing DuckLake data for this partition before re-processing- if session is not None and config.cleanup_existing_partition_data:-- def delete_persons_partition(- conn: psycopg.Connection[Any], date: datetime = partition_date- ) -> None:- delete_persons_partition_data(context, catalog, team_id, date, conn=conn)-- session.run(f"delete persons partition {date_str}", delete_persons_partition)+ if conn is not None and config.cleanup_existing_partition_data:+ delete_persons_partition_data(context, catalog, team_id, partition_date, conn=conn)def do_export(client: Client, date: datetime = partition_date) -> str | None:with tags_context(kind="dagster", dagster=tags):@@ -2134,23 +1636,10 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBaif s3_path:total_exported += 1- if session is not None:-- def register_persons_file(conn: psycopg.Connection[Any], path: str = s3_path) -> bool:- return register_persons_file_with_duckling(context, catalog, path, config, conn)-- registered_persons_file = session.run(- f"register persons file {date_str}", register_persons_file- )- else:- registered_persons_file = False- if registered_persons_file:+ if conn is not None and register_persons_file_with_duckling(+ context, catalog, s3_path, config, conn+ ):total_registered += 1- if iceberg_enabled and session is not None:- if write_partition_to_iceberg(- context, session.conn, "persons", s3_path, team_id, "_timestamp", partition_date- ):- total_iceberg += 1context.add_output_metadata({@@ -2160,7 +1649,6 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa"dates_processed": len(dates),"files_exported": total_exported,"files_registered": total_registered,- "files_iceberg_written": total_iceberg,"bucket": catalog.bucket,})@@ -2179,8 +1667,8 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa)finally:- if session is not None:- session.close()+ if conn is not None:+ conn.close()@sensor(diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 3681d32e85be..f91dba30410a 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -19,8 +19,6 @@ from posthog.dags.events_backfill_to_duckling import (PERSONS_COLUMNS,PERSONS_CONCURRENCY_TAG,PERSONS_TABLE_DDL,- _connection_dropped,- _DuckgresSession,_get_cluster,_set_table_partitioning,_validate_identifier,@@ -730,111 +728,3 @@ class TestDucklingConcurrencyTags:def test_backfill_carries_shared_concurrency_key(self, _name, tag_dict):((shared_key, shared_value),) = DUCKLING_BACKFILL_CONCURRENCY_TAG.items()assert tag_dict[shared_key] == shared_value---class TestConnectionDropped:- """_connection_dropped decides which errors mean "the worker/connection went- away, reconnect to a fresh worker" vs. a real SQL error that must propagate.- """-- @parameterized.expand(- [- ("connection_exception", psycopg.errors.ConnectionException()),- ("server_closed", psycopg.OperationalError("server closed the connection unexpectedly")),- ("connection_lost", psycopg.OperationalError("connection to server was lost")),- ]- )- def test_operational_error_connection_loss_is_dropped(self, _label, exc):- assert _connection_dropped(exc) is True-- @parameterized.expand(- [- # The exact shape the control plane surfaced when the backfill worker- # pod died mid-DELETE (gRPC Unavailable wrapping a reset socket).- ("reset", "flight execute update: rpc error: code = Unavailable desc = ...: connection reset by peer"),- ("refused", "transport: Error while dialing: dial tcp 10.0.0.1:8816: connect: connection refused"),- ("unavailable", "rpc error: code = Unavailable"),- ("reading", "error reading from server"),- ]- )- def test_internal_error_worker_gone_is_dropped(self, _label, msg):- assert _connection_dropped(psycopg.InternalError(msg)) is True-- @parameterized.expand(- [- ("constraint", "Constraint Error: duplicate key value"),- ("generic_unavailable", "Catalog Error: schema unavailable for team"),- ]- )- def test_internal_error_real_sql_error_is_not_dropped(self, _label, msg):- # A genuine engine error (not a transport failure) must propagate, not retry.- assert _connection_dropped(psycopg.InternalError(msg)) is False-- @parameterized.expand(- [- ("disk_full", psycopg.errors.DiskFull()),- ("undefined_table", psycopg.errors.UndefinedTable()),- ("value_error", ValueError("nope")),- ]- )- def test_non_connection_errors_are_not_dropped(self, _label, exc):- assert _connection_dropped(exc) is False---class TestDuckgresSessionRetry:- """_DuckgresSession reconnects to a fresh worker on a mid-statement connection- drop and replays the (idempotent) op, giving up only after MAX_ATTEMPTS.- """-- @patch("posthog.dags.events_backfill_to_duckling.time.sleep")- @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")- def test_success_runs_once_without_reconnect(self, mock_connect, _sleep):- mock_connect.return_value = MagicMock()- session = _DuckgresSession(MagicMock(), MagicMock())- op = MagicMock(return_value="ok")-- assert session.run("op", op) == "ok"- assert op.call_count == 1- assert mock_connect.call_count == 1 # only the initial connect-- @patch("posthog.dags.events_backfill_to_duckling.time.sleep")- @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")- def test_reconnects_then_succeeds(self, mock_connect, _sleep):- mock_connect.side_effect = [MagicMock(), MagicMock(), MagicMock()]- session = _DuckgresSession(MagicMock(), MagicMock())- op = MagicMock(- side_effect=[- psycopg.OperationalError("server closed the connection unexpectedly"),- psycopg.InternalError("connection reset by peer"),- "ok",- ]- )-- assert session.run("op", op) == "ok"- assert op.call_count == 3- assert mock_connect.call_count == 3 # 1 initial + 2 reconnects-- @patch("posthog.dags.events_backfill_to_duckling.time.sleep")- @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")- def test_gives_up_and_reraises_after_max_attempts(self, mock_connect, _sleep):- mock_connect.return_value = MagicMock()- session = _DuckgresSession(MagicMock(), MagicMock())- op = MagicMock(side_effect=psycopg.OperationalError("connection to server was lost"))-- with pytest.raises(psycopg.OperationalError):- session.run("op", op)- assert op.call_count == _DuckgresSession.MAX_ATTEMPTS- # initial connect + (MAX_ATTEMPTS - 1) reconnects; the last attempt does not reconnect- assert mock_connect.call_count == _DuckgresSession.MAX_ATTEMPTS-- @patch("posthog.dags.events_backfill_to_duckling.time.sleep")- @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")- def test_non_connection_error_propagates_immediately(self, mock_connect, _sleep):- mock_connect.return_value = MagicMock()- session = _DuckgresSession(MagicMock(), MagicMock())- op = MagicMock(side_effect=psycopg.InternalError("Constraint Error: duplicate key value"))-- with pytest.raises(psycopg.InternalError):- session.run("op", op)- assert op.call_count == 1- assert mock_connect.call_count == 1 # no reconnect on a real SQL errordiff --git a/products/web_analytics/backend/tasks/heatmap_screenshot.py b/products/web_analytics/backend/tasks/heatmap_screenshot.pyindex 48f310be4e8a..83d1cd4bf7f9 100644--- a/products/web_analytics/backend/tasks/heatmap_screenshot.py+++ b/products/web_analytics/backend/tasks/heatmap_screenshot.py@@ -493,21 +493,15 @@ def _launch_local_browser(p: Playwright) -> Browser:proxy_config = ProxySettings(server=proxy_url) if proxy_url else None# In the production image CHROME_BIN points at the only installed browser (/usr/bin/chromium);# Playwright's bundled browser is intentionally NOT installed. So when CHROME_BIN is set but the- # path is invalid, fail loudly with a config error rather than silently falling through to a+ # path is missing, fail loudly with a config error rather than silently falling through to a# non-existent bundled browser. When CHROME_BIN is unset (local dev), executable_path stays None# and Playwright uses its own bundled Chromium. NOTE: Playwright skips browser-version enforcement# when executable_path is set, so re-check system-chromium compatibility when bumping `playwright`.executable_path = os.environ.get("CHROME_BIN") or None- if executable_path and (not os.path.isfile(executable_path) or not os.access(executable_path, os.X_OK)):- logger.error(- "heatmap_screenshot.chrome_bin_invalid",- chrome_bin=executable_path,- exists=os.path.exists(executable_path),- is_file=os.path.isfile(executable_path),- is_executable=os.access(executable_path, os.X_OK),- )+ if executable_path and not os.path.exists(executable_path):+ logger.error("heatmap_screenshot.chrome_bin_invalid", chrome_bin=executable_path)raise ImproperlyConfigured(- f"CHROME_BIN is set to '{executable_path}' but it is not an executable file. The production "+ f"CHROME_BIN is set to '{executable_path}' but no executable exists there. The production ""image installs Chromium at /usr/bin/chromium and does not bundle a Playwright browser.")return p.chromium.launch(diff --git a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.pyindex 22b7ca385fc1..8f16ae6aaf49 100644--- a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py+++ b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py@@ -1,5 +1,4 @@import os-import tempfilefrom contextlib import contextmanagerfrom typing import Any@@ -616,12 +615,10 @@ class TestLaunchLocalBrowser(SimpleTestCase):assert p.chromium.launch.call_args.kwargs["executable_path"] is Nonedef test_uses_chrome_bin_when_it_points_at_an_existing_path(self) -> None:- with tempfile.NamedTemporaryFile() as chrome_bin:- os.chmod(chrome_bin.name, 0o755)- with patch.dict(os.environ, {"CHROME_BIN": chrome_bin.name}):- p = MagicMock()- _launch_local_browser(p)- assert p.chromium.launch.call_args.kwargs["executable_path"] == chrome_bin.name+ with patch.dict(os.environ, {"CHROME_BIN": __file__}):+ p = MagicMock()+ _launch_local_browser(p)+ assert p.chromium.launch.call_args.kwargs["executable_path"] == __file__def test_raises_config_error_when_chrome_bin_points_at_missing_path(self) -> None:with patch.dict(os.environ, {"CHROME_BIN": "/nonexistent/chromium"}):