: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(data-warehouse): retry transient database connect failures in import activities (#104473)
Tom Owers8e6388c5b222
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 4c6537c212a9..f80801c9afd8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -86,6 +86,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixTEMPORARY_HOST_RESOLUTION_PREFIX,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UNKNOWN_RESOURCE_PREFIX+from products.warehouse_sources.backend.temporal.data_imports.util import with_internal_db_retriesfrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (AcquireV3LockActivityInputs,CheckPipelineVersionActivityInputs,@@ -686,6 +687,7 @@ class CreateSourceTemplateInputs:@activity.defn+@with_internal_db_retriesdef create_source_templates(inputs: CreateSourceTemplateInputs) -> None:create_warehouse_templates_for_source(team_id=inputs.team_id, run_id=inputs.run_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.pyindex 32dce8bb7bce..d24e5502bb16 100644--- a/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/post_import_job.py@@ -45,6 +45,7 @@ from products.warehouse_sources.backend.temporal.data_imports.external_product_hdata_quality_checks_needed_for,emit_signals_enabled_for,)+from products.warehouse_sources.backend.temporal.data_imports.util import with_internal_db_retriesfrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.calculate_table_size import (CalculateTableSizeActivityInputs,calculate_table_size_activity,@@ -335,6 +336,7 @@ def _legacy_step_keys(ctx: PostImportContext) -> list[str]:@activity.defn+@with_internal_db_retriesdef resolve_post_import_context_activity(inputs: PostImportWorkflowInputs) -> PostImportContext:bind_contextvars(team_id=inputs.team_id)logger = LOGGER.bind()diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.pyindex 2df77b55704d..646796487d98 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py@@ -5,6 +5,12 @@ from types import SimpleNamespaceimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.db import (+ OperationalError as DjangoOperationalError,+ ProgrammingError,+)++import psycopgimport botocore.exceptionsimport deltalake.exceptionsfrom parameterized import parameterized@@ -13,10 +19,13 @@ from posthog.temporal.common.errors import NonReportableErrorfrom products.warehouse_sources.backend.temporal.data_imports import util as util_modulefrom products.warehouse_sources.backend.temporal.data_imports.util import (+ _INTERNAL_DB_MAX_ATTEMPTS,NonRetryableException,S3OperationError,_is_transient_s3_connection_error,prepare_s3_files_for_querying,+ retry_internal_db_operation,+ with_internal_db_retries,)# An S3 throttling response, in the two shapes it reaches these helpers in: translated by s3fs into@@ -524,3 +533,119 @@ async def test_delete_folder_treats_an_already_deleted_folder_as_done(mock_captus3._rm.assert_awaited_once()mock_capture_exception.assert_not_called()+++ [+ (+ "dns_name_not_known",+ DjangoOperationalError("connection failed: [Errno -2] Name or service not known"),+ True,+ ),+ (+ "dns_temporary_failure",+ DjangoOperationalError("connection failed: [Errno -3] Temporary failure in name resolution"),+ True,+ ),+ (+ "dns_no_address_for_hostname",+ DjangoOperationalError("[Errno -5] No address associated with hostname"),+ True,+ ),+ (+ "unwrapped_psycopg_dns_failure",+ psycopg.OperationalError("[Errno -2] Name or service not known"),+ True,+ ),+ (+ "connection_refused",+ DjangoOperationalError(+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: Connection refused'+ ),+ True,+ ),+ (+ "dropped_backend_connection",+ DjangoOperationalError("server closed the connection unexpectedly"),+ True,+ ),+ (+ "rejected_password",+ DjangoOperationalError('connection failed: FATAL: password authentication failed for user "fake_user"'),+ False,+ ),+ (+ "missing_column",+ ProgrammingError('column "invented_column" does not exist'),+ False,+ ),+ ]+)+@patch("time.sleep")+@patch(f"{_UTIL_MODULE}.close_stale_db_connections")+def test_retry_internal_db_operation_only_retries_transient_failures(+ _name: str,+ error: Exception,+ is_transient: bool,+ mock_close_connections: MagicMock,+ mock_sleep: MagicMock,+) -> None:+ # Reaching our own database can fail because the host stops resolving for a moment, or+ # refuses the connection while infrastructure moves, and a later attempt gets past it. A+ # rejected password and a missing column arrive through the same psycopg classes and never+ # get better, so they have to fail on the first attempt instead of holding the activity open+ # for the whole backoff budget.+ attempts = 0++ def operation() -> None:+ nonlocal attempts+ attempts += 1+ raise error++ with pytest.raises(type(error)):+ retry_internal_db_operation(operation)++ assert attempts == (_INTERNAL_DB_MAX_ATTEMPTS if is_transient else 1)+++@patch("time.sleep")+@patch(f"{_UTIL_MODULE}.close_stale_db_connections")+def test_retry_internal_db_operation_returns_the_result_of_a_later_attempt(+ mock_close_connections: MagicMock, mock_sleep: MagicMock+) -> None:+ # A blip that clears has to leave nothing behind for error tracking, which means the result+ # comes back from the attempt that succeeded. The broken connection is evicted first, so the+ # next attempt reconnects instead of reusing it.+ attempts = 0++ def operation() -> str:+ nonlocal attempts+ attempts += 1+ if attempts < 3:+ raise DjangoOperationalError("connection failed: [Errno -2] Name or service not known")+ return "resolved"++ assert retry_internal_db_operation(operation) == "resolved"+ assert attempts == 3+ assert mock_close_connections.call_count == 2+++@patch("time.sleep")+@patch(f"{_UTIL_MODULE}.close_stale_db_connections")+def test_with_internal_db_retries_retries_with_the_original_arguments(+ mock_close_connections: MagicMock, mock_sleep: MagicMock+) -> None:+ # Activities whose whole body is database work use the decorator form, so the retried attempt+ # has to run with the activity's own inputs rather than with none.+ attempts = 0++ @with_internal_db_retries+ def activity_body(team_id: int) -> int:+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise DjangoOperationalError("connection failed: [Errno -2] Name or service not known")+ return team_id++ assert activity_body(team_id=1234) == 1234+ assert attempts == 2diff --git a/products/warehouse_sources/backend/temporal/data_imports/util.py b/products/warehouse_sources/backend/temporal/data_imports/util.pyindex 49eb3a957430..040f0090eab7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/util.py+++ b/products/warehouse_sources/backend/temporal/data_imports/util.py@@ -1,24 +1,36 @@import re+import timeimport errnoimport asynciofrom collections.abc import Awaitable, Callablefrom datetime import datetime-from typing import Literal, Optional+from functools import wraps+from typing import Literal, Optional, ParamSpec, TypeVarfrom uuid import uuid4from django.conf import settings+from django.db import OperationalError as DjangoOperationalError+import psycopgimport botocore.exceptionsfrom structlog.types import FilteringBoundLoggerfrom posthog.exceptions import capture_exceptionfrom posthog.settings.utils import get_from_env+from posthog.temporal.common.db_errors import is_transient_db_errorfrom posthog.temporal.common.errors import NonReportableError+from posthog.temporal.common.logger import get_logger+from posthog.temporal.common.utils import close_stale_db_connectionsfrom posthog.utils import str_to_boolfrom products.data_warehouse.backend.facade.api import aget_s3_clientfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+LOGGER = get_logger(__name__)++P = ParamSpec("P")+T = TypeVar("T")+# A best-effort delete of old query folders can hit a transient S3 connectivity blip# (connect/read timeout, dropped connection). The folder is timestamped and simply gets# picked up by the age-based GC on a later sync, so these aren't worth an error-tracking@@ -119,6 +131,107 @@ class PostHogInternalDatabaseError(Exception):"""+# Transient failures reaching PostHog's own database, matched on the wording psycopg reports.+# `is_transient_db_error` deliberately leaves connect-time failures out, because it also classifies+# errors raised against a customer-supplied host, where a name that does not resolve or a port that+# refuses a connection is permanent misconfiguration. Code whose only database is ours reads the+# same wording the other way round: our host stops resolving, or refuses a connection, while+# infrastructure moves under a long-lived worker, and a later attempt reaches the database again.+# The list stays this narrow because psycopg reports a rejected password and a missing database+# through the same OperationalError class, and those must keep failing fast.+_TRANSIENT_INTERNAL_DB_MARKERS = (+ # Our host did not resolve. psycopg resolves the host itself and reports whatever+ # getaddrinfo returned, so which of these wordings arrives depends on how resolution failed+ # (EAI_NONAME, EAI_AGAIN, EAI_NODATA and EAI_FAIL respectively), and the last one is libpq's+ # equivalent. EAI_FAIL belongs here too: our host name comes from our own configuration, so a+ # resolver that answers "non-recoverable" is describing the resolver, not the name.+ "name or service not known",+ "temporary failure in name resolution",+ "no address associated with hostname",+ "non-recoverable failure in name resolution",+ "could not translate host name",+ # Nothing accepts a connection on the port, because the pooler or the database is restarting+ # or its endpoint is being re-pointed.+ "connection refused",+)++# The tightest start_to_close timeout among the activities that use this is one minute, so the+# retry budget has to stay well inside it. 4 attempts spend 14s on backoff (2+4+8s), and a failed+# attempt adds almost nothing because an unresolvable name and a refused port both fail at once.+_INTERNAL_DB_MAX_ATTEMPTS = 4+++def is_transient_internal_db_error(error: BaseException) -> bool:+ """Whether `error` is a transient failure reaching PostHog's own database.++ Only for code that talks to our database. Never classify a connection to a customer's source+ database with this, because there the same psycopg wording means the customer's host is+ misconfigured and the sync has to stop instead of retrying.+ """+ if is_transient_db_error(error):+ return True+ if not isinstance(error, DjangoOperationalError | psycopg.OperationalError):+ return False+ message = str(error).lower()+ return any(marker in message for marker in _TRANSIENT_INTERNAL_DB_MARKERS)+++def retry_internal_db_operation(operation: Callable[[], T]) -> T:+ """Run `operation`, and retry it with backoff while reaching PostHog's own database fails+ transiently.++ An activity that reads our database at its start fails through no fault of its own when the+ host briefly stops resolving or refuses a connection, and each failed attempt reports an+ exception nobody can action. Absorb the blip here, so only an exhausted budget reaches error+ tracking, where it describes a database that is really unreachable.++ `posthog.temporal.common.utils.retry_on_db_connection_drop` covers the neighboring case of a+ stale pooled connection, which one immediate retry on a fresh connection resolves. A connect+ failure needs the delay as well, because the name or the port has to become reachable first.++ Pass a zero-arg callable that produces the result, so a retry issues a fresh query:++ schema = retry_internal_db_operation(lambda: ExternalDataSchema.objects.get(id=schema_id))+ """+ attempt = 0++ while True:+ attempt += 1+ try:+ return operation()+ except Exception as e:+ if attempt >= _INTERNAL_DB_MAX_ATTEMPTS or not is_transient_internal_db_error(e):+ raise+ # A failed attempt can leave a broken connection in this worker's pool, so evict it+ # and let the next attempt reconnect.+ close_stale_db_connections()+ LOGGER.warning(+ f"Transient failure reaching PostHog's database (attempt {attempt}/{_INTERNAL_DB_MAX_ATTEMPTS}), retrying",+ exc_info=e,+ )+ time.sleep(2**attempt)+++def with_internal_db_retries(fn: Callable[P, T]) -> Callable[P, T]:+ """Decorator form of `retry_internal_db_operation`, for an activity whose whole body is+ idempotent work against PostHog's own database. Stack it under `@activity.defn`:++ @activity.defn+ @with_internal_db_retries+ def my_activity(inputs: MyInputs) -> None: ...++ An activity that also does expensive work of its own, such as an S3 listing or an extraction,+ wraps its individual queries with `retry_internal_db_operation` instead, so a blip on a late+ write does not repeat the work before it.+ """++ @wraps(fn)+ def inner(*args: P.args, **kwargs: P.kwargs) -> T:+ return retry_internal_db_operation(lambda: fn(*args, **kwargs))++ return inner++# 10 mins buffer to avoid deleting files Clickhouse may be readingS3_DELETE_TIME_BUFFER = 600diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.pyindex 14187fd5a3ee..fc8d0c0f6010 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py@@ -36,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinerelease_v3_pipeline_lock,write_v3_pipeline_lock_meta,)+from products.warehouse_sources.backend.temporal.data_imports.util import with_internal_db_retriesfrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (is_pipeline_v3_enabled,)@@ -84,6 +85,7 @@ class ReleaseV3LockActivityInputs:@activity.defn+@with_internal_db_retriesdef check_pipeline_version_activity(inputs: CheckPipelineVersionActivityInputs) -> CheckPipelineVersionActivityOutputs:bind_contextvars(team_id=inputs.team_id)close_old_connections()diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.pyindex 6b90e686d52b..80532fb74163 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py@@ -14,6 +14,7 @@ from products.data_warehouse.backend.facade.api import get_size_of_folderfrom products.warehouse_sources.backend.models import DataWarehouseTablefrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.util import retry_internal_db_operationLOGGER = get_logger(__name__)@@ -25,6 +26,9 @@ class CalculateTableSizeActivityInputs:job_id: str+# The individual queries carry `retry_internal_db_operation` rather than the whole activity+# carrying `with_internal_db_retries`, because retrying the whole body would repeat the S3 folder+# listing below, which can take minutes and still has to finish inside the activity's timeout.@activity.defndef calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> None:bind_contextvars(team_id=inputs.team_id)@@ -34,13 +38,13 @@ def calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> Nlogger.debug("Calculating table size in S3")try:- schema = ExternalDataSchema.objects.get(id=inputs.schema_id)+ schema = retry_internal_db_operation(lambda: ExternalDataSchema.objects.get(id=inputs.schema_id))except ExternalDataSchema.DoesNotExist:logger.debug(f"Schema doesnt exist, exiting early. Schema id = {inputs.schema_id}")returntry:- job = ExternalDataJob.objects.get(id=inputs.job_id)+ job = retry_internal_db_operation(lambda: ExternalDataJob.objects.get(id=inputs.job_id))except ExternalDataJob.DoesNotExist:logger.debug(f"Job doesnt exist, exiting early. Job id = {inputs.job_id}")return@@ -84,7 +88,7 @@ def calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> Njob.storage_delta_mib = table_size_deltatry:- job.save(update_fields=["storage_delta_mib", "updated_at"])+ retry_internal_db_operation(lambda: job.save(update_fields=["storage_delta_mib", "updated_at"]))except DatabaseError:# get_size_of_folder() (an S3 listing) can run long enough for the job's team to be# deleted meanwhile, cascading away this row before the UPDATE lands. Not a defect —@@ -100,7 +104,7 @@ def calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> N# possibly-stale in-memory url_pattern (table was loaded before the potentially long# get_size_of_folder() call above) against the row's current DB value, and a credential-less# table with no other change in flight trips the url_pattern guard on that false mismatch.- table.save(update_fields=["size_in_s3_mib", "updated_at"])+ retry_internal_db_operation(lambda: table.save(update_fields=["size_in_s3_mib", "updated_at"]))except DatabaseError:if not DataWarehouseTable.objects.filter(id=table.id).exists():logger.debug(f"Table was deleted while calculating table size, exiting early. Table id = {table.id}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.pyindex fca2a37730a7..4d4d7b1ce7c4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py@@ -12,6 +12,7 @@ from posthog.settings.base_variables import TESTfrom posthog.temporal.common.logger import get_loggerfrom products.warehouse_sources.backend.billing import FREE_HISTORICAL_WINDOW, FREE_PERIOD_END, FREE_PERIOD_START+from products.warehouse_sources.backend.temporal.data_imports.util import with_internal_db_retriesfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited@@ -32,6 +33,7 @@ class CheckBillingLimitsActivityInputs:@activity.defn+@with_internal_db_retriesdef check_billing_limits_activity(inputs: CheckBillingLimitsActivityInputs) -> bool:from products.warehouse_sources.backend.temporal.data_imports.external_data_job import (ExternalDataJob,