: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): add hard timeout to chdb table introspection (#68727)
Tom Owers2982353eca65
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 519615b21778..156a0421dd64 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -1,5 +1,7 @@import csv+import sysimport time+import subprocessfrom datetime import datetimefrom io import StringIOfrom typing import TYPE_CHECKING, Any, NotRequired, Optional, TypedDict, cast@@ -94,6 +96,46 @@ type DataWarehouseTableIntrospectedColumns = dict[str, DataWarehouseTableIntrosp# and never user-facing.HIDDEN_COLUMNS: frozenset[str] = frozenset({"_dlt_id", "_dlt_load_id", "_ph_debug", PARTITION_KEY})+# chdb has no query timeout, and a stalled S3 read can wedge a web worker indefinitely+# (each request also pins ~300MB of RSS for the embedded ClickHouse). Running it in a+# subprocess lets us kill it and degrade to the ClickHouse-cluster fallback.+CHDB_QUERY_TIMEOUT_SECONDS = 30.0++_CHDB_SUBPROCESS_SCRIPT = """+import sys++try:+ import chdb++ result = chdb.query(sys.stdin.read(), output_format="CSV")+except Exception as e:+ sys.stderr.write(str(e))+ sys.exit(1)++sys.stdout.write(str(result))+"""+++def run_chdb_query(query: str, timeout: float = CHDB_QUERY_TIMEOUT_SECONDS) -> str:+ # The query is passed over stdin because it embeds S3 credentials — argv is world-readable.+ # Errors are re-raised as RuntimeError with chdb's message preserved so callers'+ # error classification (e.g. _is_suppressed_chdb_error) behaves as if chdb ran in-process.+ try:+ process = subprocess.run(+ [sys.executable, "-c", _CHDB_SUBPROCESS_SCRIPT],+ input=query,+ capture_output=True,+ text=True,+ timeout=timeout,+ )+ except subprocess.TimeoutExpired:+ raise RuntimeError(f"chdb query timed out after {timeout}s")++ if process.returncode != 0:+ raise RuntimeError(process.stderr.strip() or f"chdb subprocess exited with code {process.returncode}")++ return process.stdout+class DataWarehouseTableQuerySet(models.QuerySet["DataWarehouseTable"]):def queryable(self) -> "DataWarehouseTableQuerySet":@@ -265,8 +307,6 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletself,safe_expose_ch_error: bool = True,) -> DataWarehouseTableIntrospectedColumns:- import chdb # noqa: PLC0415 - embedded ClickHouse; deferred so this model module stays off the startup path-result: list[tuple[str, ...]] | None = Noneplaceholder_context = HogQLContext(team_id=self.team.pk)s3_table_func = build_function_call(@@ -296,8 +336,8 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletchdb_query = (f"SET format_csv_allow_double_quotes = {1 if self.csv_allow_double_quotes else 0}; {chdb_query}")- chdb_result = chdb.query(chdb_query, output_format="CSV")- reader = csv.reader(StringIO(str(chdb_result)))+ chdb_result = run_chdb_query(chdb_query)+ reader = csv.reader(StringIO(chdb_result))result = [tuple(row) for row in reader]except Exception as chdb_error:if self._is_suppressed_chdb_error(chdb_error):@@ -394,8 +434,6 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletreturn Nonedef get_count(self, safe_expose_ch_error=True) -> int:- import chdb # noqa: PLC0415 - embedded ClickHouse; deferred so this model module stays off the startup path-placeholder_context = HogQLContext(team_id=self.team.pk)s3_table_func = build_function_call(url=self.url_pattern,@@ -415,8 +453,8 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet# chdb doesn't support parameterized querieschdb_query = f"SELECT count() FROM {s3_table_func}" % quoted_placeholders- chdb_result = chdb.query(chdb_query, output_format="CSV")- reader = csv.reader(StringIO(str(chdb_result)))+ chdb_result = run_chdb_query(chdb_query)+ reader = csv.reader(StringIO(chdb_result))result = [tuple(row) for row in reader]except Exception as chdb_error:capture_exception(chdb_error)diff --git a/products/warehouse_sources/backend/tests/test_table.py b/products/warehouse_sources/backend/tests/test_table.pynew file mode 100644index 000000000000..b1a4ce55779a--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_table.py@@ -0,0 +1,28 @@+import subprocess++import pytest+from unittest.mock import patch++from products.warehouse_sources.backend.models.table import DataWarehouseTable, run_chdb_query+++class TestRunChdbQuery:+ def test_hung_query_is_killed_and_raises_instead_of_blocking(self) -> None:+ # Real subprocess: chdb import alone exceeds the timeout, so this exercises the+ # actual kill path. Guards the regression where a stalled chdb S3 read wedged web+ # workers indefinitely (no timeout around the embedded query).+ with pytest.raises(RuntimeError, match="timed out"):+ run_chdb_query("SELECT sleep(2)", timeout=0.5)++ def test_suppressed_delta_error_classification_survives_subprocess_boundary(self) -> None:+ completed = subprocess.CompletedProcess(+ args=[],+ returncode=1,+ stdout="",+ stderr="Code: 36. DB::Exception: Unsupported DeltaLake type: timestamp_ntz. (BAD_ARGUMENTS)",+ )+ with patch("products.warehouse_sources.backend.models.table.subprocess.run", return_value=completed):+ with pytest.raises(RuntimeError) as exc_info:+ run_chdb_query("DESCRIBE TABLE s3('https://example.com/table/')")++ assert DataWarehouseTable()._is_suppressed_chdb_error(exc_info.value)