: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): recover SQL editor from stuck sources and corrupt Parquet (#72057)
posthog[bot]d614883466c1
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 9c6c80ad5f33..0e407f3c21ca 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -25,6 +25,7 @@ import { ChartDisplayType, InsightShortId, QueryBasedInsightModel } from '~/typeimport { editorSceneLogic } from './editorSceneLogic'import { OutputTab } from './outputPaneLogic'import { activeTabMatchesUrlTarget, getDisplayTypeToSaveInsight, sqlEditorLogic } from './sqlEditorLogic'+import { SQLEditorMode } from './sqlEditorModes'// endpointLogic uses permanentlyMount() with a keyed logic, which crashes in// tests without the full React component tree — disable auto-mounting@@ -1922,4 +1923,28 @@ describe('sqlEditorLogic', () => {})})})++ describe('stuck database load recovery', () => {+ it('forces a fresh load on mount when the shared schema loader is stuck loading', async () => {+ // databaseTableListLogic is a shared singleton, so a prior visit can leave+ // `databaseLoading` stuck true (a load that never settled). Reproduce that by making the+ // schema query hang, then mount the editor: it must force a fresh load rather than skip+ // it, otherwise the sources sidebar sits on "Loading..." forever.+ // Non-forced so the only `{ force: true }` load in the action history is the editor's —+ // the schema query hangs, so `databaseLoading` stays true regardless.+ useMocks({ post: { '/api/environments/:team_id/query/': () => new Promise(() => {}) } })+ databaseLogic.actions.loadDatabase()+ await expectLogic(databaseLogic).toMatchValues({ databaseLoading: true })++ logic = sqlEditorLogic({+ tabId: TAB_ID,+ mode: SQLEditorMode.Embedded,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ await expectLogic(logic).toDispatchActions([logic.actionCreators.loadDatabase({ force: true })])+ })+ })})diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 1643a4496d9e..5e9af60f995b 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -3484,11 +3484,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([if ((isEmbeddedSQLEditorMode(props.mode ?? SQLEditorMode.FullScene) || !hasExplicitEditorUrlState) &&- shouldSyncDatabaseConnection &&- !values.databaseLoading+ shouldSyncDatabaseConnection) {actions.setConnection(values.selectedConnectionId ?? null)- actions.loadDatabase()+ // `databaseTableListLogic` is a shared singleton. If a prior visit left `databaseLoading`+ // stuck true (a load that never settled), the plain guard would skip the reload and the+ // editor would sit on "Loading..." forever. On remount we still need data, so force a+ // fresh request to bypass any hung in-flight load.+ actions.loadDatabase(values.databaseLoading ? { force: true } : undefined)}}),beforeUnmount(({ cache, props }) => {diff --git a/posthog/errors.py b/posthog/errors.pyindex f0cb8c10fc4d..96370df812e7 100644--- a/posthog/errors.py+++ b/posthog/errors.py@@ -84,6 +84,12 @@ def clickhouse_error_type(e: Exception) -> str:STORAGE_FILE_URI_PATTERN = re.compile(r"\(in file/uri ([^)]+)\)")+CORRUPTED_PARQUET_METADATA_MESSAGE = (+ "A Parquet file backing this table has corrupted or oversized metadata and can't be read. "+ "This usually means the file wasn't written correctly during import. Re-sync the source (or "+ "re-upload the file if you manage it yourself), and contact support if it keeps happening."+)+def _wrap_storage_file_changed_error(err: ServerException) -> "CHQueryErrorS3FileChangedDuringRead":match = STORAGE_FILE_URI_PATTERN.search(err.message)@@ -135,6 +141,14 @@ def wrap_clickhouse_query_error(err: Exception) -> Exception: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)+ elif name == "STD_EXCEPTION" and "deserialize thrift" in err.message:+ # A Parquet file with corrupted or oversized thrift metadata (e.g.+ # "Couldn't deserialize thrift: TProtocolException: Exceeded size limit").+ # ClickHouse surfaces this as a raw STD_EXCEPTION (code 1001), so translate it+ # into an actionable message instead of leaking the internals.+ return CHQueryErrorCorruptedParquetMetadata(+ CORRUPTED_PARQUET_METADATA_MESSAGE, code=err.code, code_name="corrupted_parquet_metadata"+ )elif name == "TABLE_IS_READ_ONLY":# Transient: a replica dropped its ZooKeeper/Keeper session and went read-only; it self-heals.return CHQueryErrorTableIsReadOnly(err.message, code=err.code, code_name="table_is_read_only")@@ -227,6 +241,12 @@ class CHQueryErrorTableIsReadOnly(InternalCHQueryError):pass+class CHQueryErrorCorruptedParquetMetadata(ExposedCHQueryError):+ """A Parquet file backing a warehouse table has corrupted or oversized thrift metadata."""++ pass++# User query errors - these are errors caused by user input/queriesclass CHQueryErrorIllegalTypeOfArgument(ExposedCHQueryError):passdiff --git a/posthog/hogql/test/test_log_query_settings.py b/posthog/hogql/test/test_log_query_settings.pyindex 3dead9e29a44..72ef96c66b1e 100644--- a/posthog/hogql/test/test_log_query_settings.py+++ b/posthog/hogql/test/test_log_query_settings.py@@ -11,9 +11,11 @@ from posthog.hogql.query import HogQLQueryExecutorfrom posthog.errors import (CH_TRANSIENT_ERRORS,+ CHQueryErrorCorruptedParquetMetadata,CHQueryErrorTableIsReadOnly,CHQueryErrorTooManyBytes,ExposedCHQueryError,+ InternalCHQueryError,QueryErrorCategory,classify_query_error,wrap_clickhouse_query_error,@@ -138,6 +140,32 @@ class TestTooManyBytesError(ClickhouseTestMixin, APIBaseTest):assert isinstance(wrapped, CH_TRANSIENT_ERRORS)+class TestCorruptedParquetMetadataError(TestCase):+ """A Parquet file with oversized/corrupted thrift metadata surfaces as a raw STD_EXCEPTION+ (code 1001). It must be translated into a friendly, exposed error instead of leaking the raw+ ClickHouse message into the SQL editor."""++ THRIFT_MESSAGE = (+ "DB::Exception: parquet::ParquetException: Couldn't deserialize thrift: "+ "TProtocolException: Exceeded size limit. Stack trace: ..."+ )++ def test_thrift_deserialization_error_is_exposed_and_friendly(self) -> None:+ wrapped = wrap_clickhouse_query_error(ServerException(self.THRIFT_MESSAGE, code=1001))+ assert isinstance(wrapped, CHQueryErrorCorruptedParquetMetadata)+ assert isinstance(wrapped, ExposedCHQueryError)+ message = str(wrapped)+ assert "DB::Exception" not in message+ assert "thrift" not in message.lower()+ assert "corrupted or oversized metadata" in message++ def test_unrelated_std_exception_stays_internal(self) -> None:+ # The translation must be narrow: a generic STD_EXCEPTION should not be exposed to users.+ wrapped = wrap_clickhouse_query_error(ServerException("DB::Exception: something else.", code=1001))+ assert not isinstance(wrapped, CHQueryErrorCorruptedParquetMetadata)+ assert isinstance(wrapped, InternalCHQueryError)++class TestArgumentCountErrorsAreUserFacing(TestCase):"""Wrong-function-arg-count errors are user query mistakes, not internal bugs, so they mustsurface as exposed 4xx errors and be classified USER_ERROR rather than captured as internals."""diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.pyindex a8f23e81b916..e2cc5ddaf0e8 100644--- a/products/data_warehouse/backend/models/test/test_table.py+++ b/products/data_warehouse/backend/models/test/test_table.py@@ -962,6 +962,12 @@ class TestTable(BaseTest):499,"The provided file doesn't exist in the bucket",),+ (+ "corrupted_parquet_thrift",+ "DB::Exception: parquet::ParquetException: Couldn't deserialize thrift: TProtocolException: Exceeded size limit",+ 1001,+ "corrupted or oversized metadata",+ ),])def test_safe_expose_ch_error(self, _name, error_message, error_code, expected_message):diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 039cea9c4a73..9cc984411d27 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -29,7 +29,7 @@ from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_param_from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.errors import wrap_clickhouse_query_error+from posthog.errors import CORRUPTED_PARQUET_METADATA_MESSAGE, wrap_clickhouse_query_errorfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr@@ -80,6 +80,7 @@ ExtractErrors = {"Bucket or key name are invalid in S3 URI": "The provided file or bucket doesn't exist","S3 exception: `NoSuchBucket`, message: 'The specified bucket does not exist.'": "The provided bucket doesn't exist","Either the file is corrupted or this is not a parquet file": "The provided file is not in Parquet format",+ "deserialize thrift": CORRUPTED_PARQUET_METADATA_MESSAGE,"Rows have different amount of values": "The provided file has rows with different amount of values","The operation is not valid for the object's storage class": "Some files in the bucket are archived (e.g. Glacier or S3 Intelligent-Tiering archive). Restore them to Standard storage or narrow the URL pattern to exclude archived files.",}@@ -845,6 +846,10 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletraisedef _safe_expose_ch_error(self, err):+ # Match ExtractErrors against the raw ClickHouse message: wrap_clickhouse_query_error may+ # rewrite the message for some codes (e.g. STD_EXCEPTION), which would hide the substrings+ # we key on here.+ raw_message = err.message if isinstance(err, ClickHouseServerException) else str(err)err = wrap_clickhouse_query_error(err)# Capacity errors are transient — surface them so the caller can retry. Check this@@ -854,7 +859,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletraise errfor key, value in ExtractErrors.items():- if key in err.message:+ if key in raw_message:raise Exception(value)raise Exception(