: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(managed-warehouse): retry trino shadow builds after cluster oom (#114996)
posthog[bot]22eef96c12b7
diff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.pyindex 606fd0067d56..a5bb259bf6a0 100644--- a/posthog/temporal/data_modeling/activities/utils.py+++ b/posthog/temporal/data_modeling/activities/utils.py@@ -105,6 +105,9 @@ EXTERNALLY_ABORTED_MARKERS = (ABANDONED_ERROR,# the query ran and produced rows; only the publish was refusedQUALITY_BLOCKED_ERROR_PREFIX,+ # Trino killed the query because the whole cluster ran out of memory. A query over its own+ # memory limit fails with an EXCEEDED_*_MEMORY_LIMIT name and still counts.+ "name=CLUSTER_OUT_OF_MEMORY,",)STREAM_FAULT_ERROR_PREFIXES = (diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 214e722f9422..ce2da1bd82aa 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -815,6 +815,7 @@ class TestNodeSuspension:"InvalidMessageFormat: Encapsulated IPC message format must begin with continuation bytes, received: 'b'","This model has been suspended after 5 consecutive failed materializations. ""Error: InvalidMessageFormat: Arrow stream contains bytes that are not an IPC message: 'garbage'",+ 'TrinoQueryError(type=INSUFFICIENT_RESOURCES, name=CLUSTER_OUT_OF_MEMORY, message="Query killed because the cluster is out of memory. Please try again in a few minutes.", query_id=20261011_000000_00000_abcde)',],)async def test_externally_aborted_failures_do_not_suspend(self, ateam, anode, asaved_query, adag, aborted_error):diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.pyindex 263737bfb0a8..5fc3ab254ebb 100644--- a/products/managed_warehouse/backend/facade/client.py+++ b/products/managed_warehouse/backend/facade/client.py@@ -241,13 +241,13 @@ async def execute_trino_model(incremental: TrinoIncrementalWrite | None = None,) -> DuckLakeTableResult:from products.managed_warehouse.backend.trino_execution import ( # noqa: PLC0415 -- keeps executor creation off startup paths- run_trino_model,+ run_trino_model_with_retries,)from products.managed_warehouse.backend.trino_materialization import ( # noqa: PLC0415 -- keeps the optional Trino driver off startup pathsexecute_trino_shadow_materialization,)- return await run_trino_model(+ return await run_trino_model_with_retries(lambda control: execute_trino_shadow_materialization(organization_id=organization_id,team_id=team_id,diff --git a/products/managed_warehouse/backend/tests/test_trino_execution.py b/products/managed_warehouse/backend/tests/test_trino_execution.pyindex 9feaae3d45c5..3b8d10434ef7 100644--- a/products/managed_warehouse/backend/tests/test_trino_execution.py+++ b/products/managed_warehouse/backend/tests/test_trino_execution.py@@ -4,6 +4,8 @@ import threadingimport pytestfrom unittest.mock import MagicMock, patch+from trino.exceptions import TrinoQueryError+from products.managed_warehouse.backend import trino_execution as execution@@ -59,3 +61,26 @@ async def test_cancellation_reaches_cursor_and_waits_for_cleanup(deadline_expire@pytest.mark.asyncioasync def test_success_preserves_result() -> None:assert await execution.run_trino_model(lambda control: 42, query_seconds=60) == 42+++ "error_name,expected_attempts",+ [("CLUSTER_OUT_OF_MEMORY", 2), ("EXCEEDED_LOCAL_MEMORY_LIMIT", 1)],+)+async def test_retries_only_cluster_out_of_memory(error_name: str, expected_attempts: int) -> None:+ attempts = 0++ def execute(control: execution.TrinoQueryControl) -> int:+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise TrinoQueryError({"errorName": error_name, "message": "Query killed"})+ return 42++ if expected_attempts == 1:+ with pytest.raises(TrinoQueryError):+ await execution.run_trino_model_with_retries(execute, query_seconds=60, retry_delays=(0,))+ else:+ assert await execution.run_trino_model_with_retries(execute, query_seconds=60, retry_delays=(0,)) == 42+ assert attempts == expected_attemptsdiff --git a/products/managed_warehouse/backend/trino_execution.py b/products/managed_warehouse/backend/trino_execution.pyindex ede6e2102906..6b1833dba319 100644--- a/products/managed_warehouse/backend/trino_execution.py+++ b/products/managed_warehouse/backend/trino_execution.py@@ -6,6 +6,8 @@ from concurrent.futures import ThreadPoolExecutorfrom time import monotonicfrom typing import TYPE_CHECKING, TypeVar+import structlog+from posthog.sync import database_sync_to_async_poolif TYPE_CHECKING:@@ -16,8 +18,14 @@ if TYPE_CHECKING:_Result = TypeVar("_Result")TRINO_QUERY_SECONDS = 6 * 60 * 60+# Trino's low-memory killer stops a query when the whole cluster runs out of memory, and asks the+# client to try again in a few minutes. A query over its own memory limit fails with another name.+CLUSTER_OUT_OF_MEMORY = "CLUSTER_OUT_OF_MEMORY"+CLUSTER_OUT_OF_MEMORY_RETRY_DELAYS_SECONDS = (2 * 60, 5 * 60)_executor = ThreadPoolExecutor(thread_name_prefix="trino-model")+logger = structlog.get_logger(__name__)+class TrinoQueryControl:def __init__(self, query_seconds: float = TRINO_QUERY_SECONDS) -> None:@@ -72,3 +80,26 @@ async def run_trino_model(raisefinally:control.finished.set()+++def is_cluster_out_of_memory(error: BaseException) -> bool:+ return getattr(error, "error_name", None) == CLUSTER_OUT_OF_MEMORY+++async def run_trino_model_with_retries(+ execute: Callable[[TrinoQueryControl], _Result],+ *,+ query_seconds: float = TRINO_QUERY_SECONDS,+ retry_delays: tuple[float, ...] = CLUSTER_OUT_OF_MEMORY_RETRY_DELAYS_SECONDS,+) -> _Result:+ """Run ``execute`` again after a cluster out-of-memory kill. All attempts share one deadline."""+ deadline = monotonic() + query_seconds+ for delay in retry_delays:+ try:+ return await run_trino_model(execute, query_seconds=deadline - monotonic())+ except Exception as error:+ if not is_cluster_out_of_memory(error) or monotonic() + delay >= deadline:+ raise+ logger.warning("Trino cluster is out of memory, retrying the model", retry_in_seconds=delay)+ await asyncio.sleep(delay)+ return await run_trino_model(execute, query_seconds=deadline - monotonic())