: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
fix(batch-exports): stop postgres merges from waiting on row locks (#106065)
Ross841fd34204f4
diff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.pyindex c9bb8d077753..cd054d8f125b 100644--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py@@ -135,8 +135,13 @@ NON_RETRYABLE_ERROR_TYPES = (# The inputs are missing required connection details (e.g. credentials or host).# This usually means the backing integration is misconfigured or absent, so retrying won't help."PostgreSQLMissingRequiredInputsError",+ # The final merge waited on locks or hit the destination's statement timeout after several attempts.+ "PostgreSQLMergeTimeoutError",)+MERGE_LOCK_TIMEOUT_SECONDS = 5 * 60+MERGE_MAX_ATTEMPTS = 3+class PostgreSQLConnectionError(Exception):pass@@ -161,6 +166,10 @@ class PostgreSQLTransactionError(Exception):super().__init__(f"A transaction failed to complete after {max_attempts} attempts: {err_msg}")+class PostgreSQLMergeTimeoutError(Exception):+ """Raised when the final merge waits on locks or exceeds the statement timeout after several attempts."""++class PostgreSQLMissingRequiredInputsError(Exception):"""Raised when the export is missing required connection inputs (credentials or host/port).@@ -218,6 +227,18 @@ class PostgresInsertInputs(BatchExportInsertInputs):)+def _table_identifier(schema: str, table_name: str) -> sql.Identifier:+ return sql.Identifier(schema, table_name) if schema else sql.Identifier(table_name)+++def _join_field_names(fields: Fields) -> sql.Composed:+ return sql.SQL(",").join(sql.Identifier(field[0]) for field in fields)+++def _is_statement_timeout(err: Exception) -> bool:+ return isinstance(err, psycopg.errors.QueryCanceled) and "statement timeout" in (err.diag.message_primary or "")++async def run_in_retryable_transaction(connection: psycopg.AsyncConnection,fn: collections.abc.Callable[[], collections.abc.Awaitable[_TransactionResult]],@@ -506,63 +527,31 @@ class PostgreSQLClient:if delete is True:await self.adelete_table(schema, table_name, not_found_ok)- async def amerge_mutable_tables(- self,- final_table_name: str,- stage_table_name: str,- schema: str,+ @staticmethod+ def _build_merge_query(+ final_table: sql.Identifier,+ stage_table: sql.Identifier,merge_key: Fields,update_key: Fields,update_when_matched: Fields,- timeout: float | int | None = None,- ) -> None:- """Merge two identical person model tables in PostgreSQL.-- Merging utilizes PostgreSQL's `INSERT INTO ... ON CONFLICT` statement. PostgreSQL version- 15 and later supports a `MERGE` command, but to ensure support for older versions of PostgreSQL- we do not use it. There are differences in the way concurrency is managed in `MERGE` but those- are less relevant concerns for us than compatibility.- """- if schema:- final_table_identifier = sql.Identifier(schema, final_table_name)- stage_table_identifier = sql.Identifier(schema, stage_table_name)-- else:- final_table_identifier = sql.Identifier(final_table_name)- stage_table_identifier = sql.Identifier(stage_table_name)-- and_separator = sql.SQL(" AND ")- merge_condition = and_separator.join(- sql.SQL("{final_field} = {stage_field}").format(- final_field=sql.Identifier("final", field[0]),- stage_field=sql.Identifier(schema, stage_table_name, field[0]),- )- for field in merge_key- )-- order_by = sql.SQL(",").join(sql.Identifier(field[0]) for field in merge_key)-- or_separator = sql.SQL(" OR ")- update_condition = or_separator.join(+ ) -> sql.Composed:+ merge_key_names = _join_field_names(merge_key)+ update_condition = sql.SQL(" OR ").join(sql.SQL("EXCLUDED.{stage_field} > final.{final_field}").format(final_field=sql.Identifier(field[0]),stage_field=sql.Identifier(field[0]),)for field in update_key)-- comma = sql.SQL(",")- update_clause = comma.join(+ update_clause = sql.SQL(",").join(sql.SQL("{final_field} = EXCLUDED.{stage_field}").format(final_field=sql.Identifier(field[0]),stage_field=sql.Identifier(field[0]),)for field in update_when_matched)- field_names = comma.join(sql.Identifier(field[0]) for field in update_when_matched)- conflict_fields = comma.join(sql.Identifier(field[0]) for field in merge_key)- merge_query = sql.SQL(+ return sql.SQL("""\INSERT INTO {final_table} AS final ({field_names})SELECT {field_names} FROM {stage_table}@@ -572,36 +561,108 @@ class PostgreSQLClient:WHERE ({update_condition})""").format(- final_table=final_table_identifier,- order_by=order_by,- conflict_fields=conflict_fields,- stage_table=stage_table_identifier,- merge_condition=merge_condition,+ final_table=final_table,+ order_by=merge_key_names,+ conflict_fields=merge_key_names,+ stage_table=stage_table,update_condition=update_condition,update_clause=update_clause,- field_names=field_names,+ field_names=_join_field_names(update_when_matched),)+ async def _amerge_once(+ self,+ merge_query: sql.Composed,+ schema: str,+ lock_timeout: float | int,+ ) -> None:+ """Run one merge attempt in its own transaction."""async with self.connection.transaction():async with self.connection.cursor() as cursor:if schema:await cursor.execute(sql.SQL("SET search_path TO {schema}").format(schema=sql.Identifier(schema)))await cursor.execute("SET TRANSACTION READ WRITE")+ # The nested transaction() is a savepoint. If the server rejects the SET, only the savepoint rolls+ # back and the merge transaction stays usable. The merge then runs as before, without a lock limit.try:- async with asyncio.timeout(timeout):- await cursor.execute(merge_query)- except psycopg.errors.InvalidColumnReference:- raise MissingPrimaryKeyError(final_table_identifier, conflict_fields)- except TimeoutError as e:- self.external_logger.exception(- "Final merge into '%s.%s' is taking too long to complete and will be rolled-back. Perhaps the database is under too much load?",- schema,- final_table_name,- )- raise TimeoutError(- f"Timed-out final merge into '{schema}.{final_table_name}' after {timeout} seconds"- ) from e+ async with self.connection.transaction():+ await cursor.execute(+ sql.SQL("SET LOCAL lock_timeout = {}").format(sql.Literal(f"{int(lock_timeout * 1000)}ms"))+ )+ except psycopg.Error:+ self.logger.warning("Failed to set lock_timeout for merge", exc_info=True)++ await cursor.execute(merge_query)++ async def amerge_mutable_tables(+ self,+ final_table_name: str,+ stage_table_name: str,+ schema: str,+ merge_key: Fields,+ update_key: Fields,+ update_when_matched: Fields,+ timeout: float | int | None = None,+ lock_timeout: float | int = MERGE_LOCK_TIMEOUT_SECONDS,+ max_attempts: int = MERGE_MAX_ATTEMPTS,+ ) -> None:+ """Merge two identical person model tables in PostgreSQL.++ Merging utilizes PostgreSQL's `INSERT INTO ... ON CONFLICT` statement. PostgreSQL version+ 15 and later supports a `MERGE` command, but to ensure support for older versions of PostgreSQL+ we do not use it. There are differences in the way concurrency is managed in `MERGE` but those+ are less relevant concerns for us than compatibility.+ """+ final_table = _table_identifier(schema, final_table_name)+ stage_table = _table_identifier(schema, stage_table_name)+ merge_query = self._build_merge_query(+ final_table=final_table,+ stage_table=stage_table,+ merge_key=merge_key,+ update_key=update_key,+ update_when_matched=update_when_matched,+ )+ merge_with_retries = make_retryable_with_exponential_backoff(+ self._amerge_once,+ max_attempts=max_attempts,+ retryable_exceptions=(psycopg.errors.LockNotAvailable, psycopg.errors.QueryCanceled),+ is_exception_retryable=lambda err: (+ isinstance(err, psycopg.errors.LockNotAvailable) or _is_statement_timeout(err)+ ),+ )++ try:+ async with asyncio.timeout(timeout):+ await merge_with_retries(merge_query, schema, lock_timeout)+ except psycopg.errors.InvalidColumnReference:+ raise MissingPrimaryKeyError(final_table, _join_field_names(merge_key))+ except TimeoutError as e:+ self.external_logger.exception(+ "Final merge into '%s.%s' is taking too long to complete and will be rolled-back. Perhaps the database is under too much load?",+ schema,+ final_table_name,+ )+ raise TimeoutError(+ f"Timed-out final merge into '{schema}.{final_table_name}' after {timeout} seconds"+ ) from e+ except psycopg.errors.LockNotAvailable as err:+ raise PostgreSQLMergeTimeoutError(+ f"Final merge into '{schema}.{final_table_name}' waited more than {lock_timeout} seconds for a lock "+ f"held by another session, after {max_attempts} attempts. "+ "A long-running or idle transaction on the destination database can hold these locks. "+ "To find the blocking session, query 'pg_stat_activity' together with 'pg_blocking_pids()'."+ ) from err+ except psycopg.errors.QueryCanceled as err:+ if not _is_statement_timeout(err):+ raise+ raise PostgreSQLMergeTimeoutError(+ f"The 'statement_timeout' of the destination database canceled the final merge into "+ f"'{schema}.{final_table_name}' after {max_attempts} attempts. "+ "The merge can be slow, or it can wait for a lock held by another session. "+ "Increase 'statement_timeout' for this user, or query 'pg_stat_activity' together with "+ "'pg_blocking_pids()' to find a blocking session."+ ) from errasync def copy_tsv_to_postgres(self,diff --git a/products/batch_exports/backend/tests/temporal/destinations/postgres/test_postgres_client.py b/products/batch_exports/backend/tests/temporal/destinations/postgres/test_postgres_client.pyindex 8cdfaf323ab6..4f20f323c92c 100644--- a/products/batch_exports/backend/tests/temporal/destinations/postgres/test_postgres_client.py+++ b/products/batch_exports/backend/tests/temporal/destinations/postgres/test_postgres_client.py@@ -1,7 +1,10 @@+import typingimport pathlibimport pytest+import psycopg+from psycopg import sqlfrom psycopg.errors import SerializationFailurefrom posthog.models.integration import MISSING_CERT_PATH, PostgreSQLIntegration@@ -10,6 +13,7 @@ from products.batch_exports.backend.temporal.destinations.postgres_batch_exportNON_RETRYABLE_ERROR_TYPES,PostgresInsertInputs,PostgreSQLClient,+ PostgreSQLMergeTimeoutError,PostgreSQLMissingRequiredInputsError,PostgreSQLTransactionError,remove_invalid_json,@@ -200,3 +204,49 @@ async def test_client_from_integration(postgres_config, setup_postgres_test_db,await cursor.execute("SELECT 1")results = await cursor.fetchall()assert results == [(1,)]+++async def test_amerge_mutable_tables_raises_non_retryable_error_when_a_row_lock_blocks_it(+ postgres_config: dict[str, typing.Any], postgres_connection: psycopg.AsyncConnection+) -> None:+ schema = postgres_config["schema"]+ final_table = sql.Identifier(schema, "merge_lock_final")+ stage_table = sql.Identifier(schema, "merge_lock_stage")++ async with postgres_connection.cursor() as cursor:+ for table in (final_table, stage_table):+ await cursor.execute(+ sql.SQL("CREATE TABLE {} (id INTEGER PRIMARY KEY, version INTEGER NOT NULL)").format(table)+ )+ await cursor.execute(sql.SQL("INSERT INTO {} VALUES (1, 1)").format(final_table))+ await cursor.execute(sql.SQL("INSERT INTO {} VALUES (1, 2)").format(stage_table))++ postgres_client = PostgreSQLClient(+ user=postgres_config["user"],+ password=postgres_config["password"],+ database=postgres_config["database"],+ host=postgres_config["host"],+ port=postgres_config["port"],+ ssl_mode="prefer",+ )++ async with postgres_connection.transaction():+ async with postgres_connection.cursor() as cursor:+ await cursor.execute(sql.SQL("SELECT * FROM {} WHERE id = 1 FOR UPDATE").format(final_table))++ async with postgres_client.connect() as pg_client:+ with pytest.raises(PostgreSQLMergeTimeoutError) as exc_info:+ await pg_client.amerge_mutable_tables(+ final_table_name="merge_lock_final",+ stage_table_name="merge_lock_stage",+ schema=schema,+ merge_key=[("id", "INTEGER")],+ update_key=[("version", "INTEGER")],+ update_when_matched=[("id", "INTEGER"), ("version", "INTEGER")],+ timeout=60,+ lock_timeout=1,+ max_attempts=1,+ )++ assert isinstance(exc_info.value.__cause__, psycopg.errors.LockNotAvailable)+ assert type(exc_info.value).__name__ in NON_RETRYABLE_ERROR_TYPES