: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): expose S3 file-changed errors on warehouse reads (#70583)
Thiago Salvatore959487a0a17f
diff --git a/ee/clickhouse/test/test_error.py b/ee/clickhouse/test/test_error.pyindex b334c00188f2..3a8af16c6676 100644--- a/ee/clickhouse/test/test_error.py+++ b/ee/clickhouse/test/test_error.py@@ -80,6 +80,50 @@ from posthog.errors import clickhouse_error_type, wrap_clickhouse_query_error499,"CHQueryErrorS3Error",),+ (+ ServerException(+ "Code: 499. DB::Exception: Unable to parse ExceptionName: InvalidRange Message: The requested range is not satisfiable: (in file/uri some-bucket/mongo/users.6.parquet): While executing ParquetV3BlockInputFormat: While executing ReadFromObjectStorage. Stack trace:\n\n0. DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x00000000141cccd0",+ code=499,+ ),+ "CHQueryErrorS3FileChangedDuringRead",+ "A file backing a data warehouse table changed while the query was reading it (some-bucket/mongo/users.6.parquet). "+ "Retry the query. If you manage these files yourself, avoid overwriting files in place: "+ "upload new files and delete old ones instead.",+ 499,+ "CHQueryErrorS3Error",+ ),+ (+ ServerException(+ "Code: 117. DB::Exception: Not a Parquet file (wrong magic bytes at the end of file): (in file/uri some-bucket/mongo/users.52.parquet): While executing ParquetV3BlockInputFormat. Stack trace:\n\n0. DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x00000000141cccd0",+ code=117,+ ),+ "CHQueryErrorS3FileChangedDuringRead",+ "A file backing a data warehouse table changed while the query was reading it (some-bucket/mongo/users.52.parquet). "+ "Retry the query. If you manage these files yourself, avoid overwriting files in place: "+ "upload new files and delete old ones instead.",+ 117,+ "CHQueryErrorIncorrectData",+ ),+ (+ ServerException(+ "DB::Exception: Cannot read all data. Bytes read: 5. Bytes expected: 100.",+ code=117,+ ),+ "CHQueryErrorIncorrectData",+ "Code: 117.\nDB::Exception: Cannot read all data. Bytes read: 5. Bytes expected: 100.",+ 117,+ "CHQueryErrorIncorrectData",+ ),+ (+ ServerException(+ "Code: 467. DB::Exception: Cannot parse boolean value here: 'null', should be 'true' or 'false' controlled by setting bool_true_representation and bool_false_representation: while converting 'null' to Bool. Stack trace:\n\n0. DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x00000000141cccd0",+ code=467,+ ),+ "CHQueryErrorCannotParseBool",+ "Cannot parse boolean value here: 'null', should be 'true' or 'false' controlled by setting bool_true_representation and bool_false_representation: while converting 'null' to Bool.",+ 467,+ "CHQueryErrorCannotParseBool",+ ),(ServerException("Code: 43. DB::Exception: Illegal type String of argument of function toInt64.",diff --git a/posthog/errors.py b/posthog/errors.pyindex 1d99a6f86437..5fee0fe43e91 100644--- a/posthog/errors.py+++ b/posthog/errors.py@@ -82,6 +82,21 @@ def clickhouse_error_type(e: Exception) -> str:return f"CHQueryError{look_up_clickhouse_error_code_meta(e).label}"+STORAGE_FILE_URI_PATTERN = re.compile(r"\(in file/uri ([^)]+)\)")+++def _wrap_storage_file_changed_error(err: ServerException) -> "CHQueryErrorS3FileChangedDuringRead":+ match = STORAGE_FILE_URI_PATTERN.search(err.message)+ file_uri = match.group(1) if match else "unknown file"+ return CHQueryErrorS3FileChangedDuringRead(+ f"A file backing a data warehouse table changed while the query was reading it ({file_uri}). "+ "Retry the query. If you manage these files yourself, avoid overwriting files in place: "+ "upload new files and delete old ones instead.",+ code=err.code,+ code_name="s3_file_changed_during_read",+ )++def wrap_clickhouse_query_error(err: Exception) -> Exception:"Beautifies clickhouse client errors, using custom error classes for every code"if not isinstance(err, ServerException):@@ -115,7 +130,11 @@ def wrap_clickhouse_query_error(err: Exception) -> Exception:detail=f"{detail} Try reducing its scope by changing the time range.")elif name == "S3_ERROR":+ if "The requested range is not satisfiable" in err.message:+ return _wrap_storage_file_changed_error(err)return CHQueryErrorS3Error(f"S3 error occurred. ({err.message})", code=err.code)+ elif name == "INCORRECT_DATA" and "Not a Parquet file" in err.message and "(in file/uri" in err.message:+ return _wrap_storage_file_changed_error(err)# user query errors - pass through original message with proper code_nameelif name == "ILLEGAL_TYPE_OF_ARGUMENT":@@ -140,6 +159,8 @@ def wrap_clickhouse_query_error(err: Exception) -> Exception:return CHQueryErrorTooManyBytes(err.message, code=err.code, code_name="too_many_bytes")elif name == "CANNOT_PARSE_UUID":return CHQueryErrorCannotParseUuid(err.message, code=err.code, code_name="cannot_parse_uuid")+ elif name == "CANNOT_PARSE_BOOL":+ return CHQueryErrorCannotParseBool(err.message, code=err.code, code_name="cannot_parse_bool")elif name == "UNSUPPORTED_METHOD":return CHQueryErrorUnsupportedMethod(err.message, code=err.code, code_name="unsupported_method")elif name == "INVALID_JOIN_ON_EXPRESSION":@@ -201,6 +222,12 @@ class CHQueryErrorS3Error(InternalCHQueryError):pass+class CHQueryErrorS3FileChangedDuringRead(ExposedCHQueryError):+ """A file backing a warehouse table was overwritten or deleted while ClickHouse was reading it."""++ pass++# User query errors - these are errors caused by user input/queriesclass CHQueryErrorIllegalTypeOfArgument(ExposedCHQueryError):pass@@ -242,6 +269,10 @@ class CHQueryErrorCannotParseUuid(InternalCHQueryError):pass+class CHQueryErrorCannotParseBool(ExposedCHQueryError):+ pass++class CHQueryErrorUnsupportedMethod(InternalCHQueryError):pass@@ -969,4 +1000,9 @@ CLICKHOUSE_ERROR_CODE_LOOKUP: dict[int, ErrorCodeMeta] = {# Transient ClickHouse infrastructure errors that are safe to retry.# This can be used in things like celery `autoretry_for` to increase resiliency.-CH_TRANSIENT_ERRORS = (CHQueryErrorTooManySimultaneousQueries, CHQueryErrorCannotScheduleTask, CHQueryErrorS3Error)+CH_TRANSIENT_ERRORS = (+ CHQueryErrorTooManySimultaneousQueries,+ CHQueryErrorCannotScheduleTask,+ CHQueryErrorS3Error,+ CHQueryErrorS3FileChangedDuringRead,+)diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex 530a1e7da133..2b95eeb2d94f 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -1,5 +1,6 @@import dataclasses-from typing import ClassVar, Literal, Optional, Union, cast+from time import sleep+from typing import Any, ClassVar, Literal, Optional, Union, castfrom opentelemetry import trace@@ -55,7 +56,7 @@ from posthog.hogql.warehouse_warnings import record_warningsfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import ClickHouseUser, Workloadfrom posthog.clickhouse.query_tagging import tag_queries-from posthog.errors import ExposedCHQueryError+from posthog.errors import CHQueryErrorS3Error, CHQueryErrorS3FileChangedDuringRead, ExposedCHQueryErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -64,6 +65,8 @@ from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEtracer = trace.get_tracer(__name__)+TRANSIENT_S3_ERROR_RETRY_DELAY_SECONDS = 1.0+@dataclasses.dataclassclass HogQLQueryExecutor:@@ -630,8 +633,8 @@ class HogQLQueryExecutor:if workload == Workload.DEFAULT and clickhouse_context.workload is not None:workload = clickhouse_context.workload- try:- self.results, self.types = sync_execute(+ def run_clickhouse_query() -> Any:+ return sync_execute(self.clickhouse_sql,clickhouse_context.values,with_column_types=True,@@ -641,6 +644,14 @@ class HogQLQueryExecutor:ch_user=self.ch_user,external_tables=list(clickhouse_context.external_tables.values()) or None,)++ try:+ try:+ self.results, self.types = run_clickhouse_query()+ except (CHQueryErrorS3Error, CHQueryErrorS3FileChangedDuringRead):+ # Files backing a warehouse table can be replaced mid-read; one retry re-lists them+ sleep(TRANSIENT_S3_ERROR_RETRY_DELAY_SECONDS)+ self.results, self.types = run_clickhouse_query()except Exception as e:if self.debug:self.results = []diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.pyindex 8352ac51157a..a9b6cd7e7438 100644--- a/posthog/hogql/test/test_query.py+++ b/posthog/hogql/test/test_query.py@@ -35,7 +35,7 @@ from posthog.hogql.test.utils import (pretty_print_response_in_tests,)-from posthog.errors import InternalCHQueryError+from posthog.errors import CHQueryErrorS3Error, InternalCHQueryErrorfrom posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODESfrom posthog.models.utils import UUIDT, uuid7from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary@@ -2089,3 +2089,41 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.error, "debug failure")self.assertEqual(response.clickhouse, "")mock_sync_execute.assert_not_called()++ def test_transient_s3_error_is_retried_once(self):+ transient_error = CHQueryErrorS3Error("S3 error occurred.", code=499)+ with (+ patch(+ "posthog.hogql.query.sync_execute", side_effect=[transient_error, ([(1,)], [("1", "UInt8")])]+ ) as mock_sync_execute,+ patch("posthog.hogql.query.sleep") as mock_sleep,+ ):+ response = execute_hogql_query("SELECT 1", team=self.team)++ self.assertEqual(response.results, [(1,)])+ self.assertEqual(mock_sync_execute.call_count, 2)+ mock_sleep.assert_called_once()++ def test_transient_s3_error_raises_after_retry_fails(self):+ transient_error = CHQueryErrorS3Error("S3 error occurred.", code=499)+ with (+ patch("posthog.hogql.query.sync_execute", side_effect=transient_error) as mock_sync_execute,+ patch("posthog.hogql.query.sleep"),+ ):+ with self.assertRaises(CHQueryErrorS3Error):+ execute_hogql_query("SELECT 1", team=self.team)++ self.assertEqual(mock_sync_execute.call_count, 2)++ def test_non_transient_errors_are_not_retried(self):+ with (+ patch(+ "posthog.hogql.query.sync_execute", side_effect=InternalCHQueryError("Unknown error.", code=1000)+ ) as mock_sync_execute,+ patch("posthog.hogql.query.sleep") as mock_sleep,+ ):+ with self.assertRaises(InternalCHQueryError):+ execute_hogql_query("SELECT 1", team=self.team)++ self.assertEqual(mock_sync_execute.call_count, 1)+ mock_sleep.assert_not_called()diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex 0dd3130cd0d6..78394acc1c2e 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -15,7 +15,12 @@ from prometheus_client import Counter, Gauge, Histogramfrom posthog.api.monitoring import Featurefrom posthog.clickhouse import query_taggingfrom posthog.clickhouse.query_tagging import QueryTags, update_tags-from posthog.errors import CHQueryErrorCannotScheduleTask, CHQueryErrorS3Error, CHQueryErrorTooManySimultaneousQueries+from posthog.errors import (+ CHQueryErrorCannotScheduleTask,+ CHQueryErrorS3Error,+ CHQueryErrorS3FileChangedDuringRead,+ CHQueryErrorTooManySimultaneousQueries,+)from posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Team@@ -430,6 +435,7 @@ def _enqueue_single_cohort_calculation(cohort: Cohort, initiating_user: OptionalCHQueryErrorCannotScheduleTask,ClickHouseAtCapacity,CHQueryErrorS3Error,+ CHQueryErrorS3FileChangedDuringRead,),retry_backoff=60,retry_backoff_max=1800,