: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(warehouse): explain Trino schema discovery failures (#93740)
posthog[bot]ad5d8ae995e0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.pyindex c35f586b2870..04404f9c687e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/source.py@@ -20,9 +20,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.regfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trino import TrinoSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.trino.trino import (+ TRINO_KNOWN_ERROR_MESSAGES,+ TrinoSchemaDiscoveryError,connect_trino,discover_trino_schemas,trino_error_to_message,+ trino_failures_as_discovery_error,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -212,7 +215,7 @@ class TrinoSource(SimpleSource[TrinoSourceConfig], ValidateDatabaseHostMixin):is_valid, error = self.is_database_host_valid(config.host, team_id)if not is_valid:raise ValueError(error or "Invalid Trino host.")- with connect_trino(config) as connection:+ with trino_failures_as_discovery_error(), connect_trino(config) as connection:discovered = discover_trino_schemas(connection.cursor(), config, names)return [SourceSchema(@@ -226,3 +229,19 @@ class TrinoSource(SimpleSource[TrinoSourceConfig], ValidateDatabaseHostMixin):)for table in discovered]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Schema discovery hands back Trino's own verdict, so the API must show it. The message keys+ # match in every consumer, because `str(TrinoSchemaDiscoveryError(...))` is the message. The+ # last key stops PostHog filing an unrecognized Trino-side failure, which is the remote+ # server's fault.+ #+ # NOTE: that last key only takes effect in the refresh-schemas classifier, which compares+ # against `f"{type(error).__name__}: {message}"`. A message-only consumer such as+ # `incremental_fields` compares against `str(e)`, so an unrecognized failure there is still+ # filed. Closing that gap needs a shared classifier across the schema-discovery views, not a+ # per-source key. Mirrors the note on the Stripe source.+ return {+ **{message: message for message in TRINO_KNOWN_ERROR_MESSAGES},+ TrinoSchemaDiscoveryError.__name__: None,+ }diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.pyindex 734a44af89e9..bc9b50590d9e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py@@ -1,15 +1,24 @@+from contextlib import nullcontext+import pytestfrom unittest.mock import MagicMock, patch+from trino.exceptions import TrinoExternalError++from products.warehouse_sources.backend.presentation.views.external_data_source import _classify_refresh_schemas_errorfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trino import (TrinoAuthTypeConfig,TrinoSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.trino.source import TrinoSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.trino.trino import (+ TRINO_ACCESS_CONTROL_UNAVAILABLE_ERROR,+ TRINO_ACCESS_DENIED_ERROR,+ TRINO_AUTHENTICATION_ERROR,TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR,DiscoveredTrinoTable,TrinoColumn,+ TrinoSchemaDiscoveryError,connect_trino,discover_trino_schemas,trino_error_to_message,@@ -148,6 +157,86 @@ def test_trino_error_to_message_preserves_tls_verification_action() -> None:assert trino_error_to_message(error) == TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR+ ("raw_error", "expected"),+ [+ ("TrinoExternalError: Failed to query OPA backend", TRINO_ACCESS_CONTROL_UNAVAILABLE_ERROR),+ ("Access Denied: Cannot select from table hive.analytics.events", TRINO_ACCESS_DENIED_ERROR),+ ("Authentication failed for user posthog", TRINO_AUTHENTICATION_ERROR),+ ("error 401", TRINO_AUTHENTICATION_ERROR),+ # A Trino query error's text carries a query ID (YYYYMMDD_HHMMSS_seq_random). The "401" in+ # its time part must not turn an access denial into an authentication error.+ (+ 'TrinoUserError(type=USER_ERROR, name=PERMISSION_DENIED, message="Access Denied: '+ 'Cannot select from table hive.analytics.events", query_id=20260902_123401_00000_abcde)',+ TRINO_ACCESS_DENIED_ERROR,+ ),+ ],+)+def test_trino_error_to_message_explains_access_failures(raw_error: str, expected: str) -> None:+ assert trino_error_to_message(RuntimeError(raw_error)) == expected+++def _trino_external_error(message: str) -> TrinoExternalError:+ return TrinoExternalError(+ {+ "message": message,+ "errorName": "EXTERNAL",+ "errorCode": 65536,+ "errorType": "EXTERNAL",+ "failureInfo": {},+ },+ "20260902_120000_00000_abcde",+ )+++def test_get_schemas_reports_what_trino_said_without_an_exception_report() -> None:+ source = TrinoSource()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.trino.source.connect_trino",+ side_effect=_trino_external_error("Failed to query OPA backend"),+ ),+ pytest.raises(TrinoSchemaDiscoveryError) as raised,+ ):+ source.get_schemas(_config(), team_id=1)++ message, is_expected_source_error = _classify_refresh_schemas_error(source, raised.value)+ assert message == TRINO_ACCESS_CONTROL_UNAVAILABLE_ERROR+ assert is_expected_source_error is True+++def test_get_schemas_leaves_a_posthog_side_failure_for_error_tracking() -> None:+ source = TrinoSource()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.trino.source.connect_trino",+ return_value=nullcontext(MagicMock()),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.trino.source.discover_trino_schemas",+ side_effect=ValueError("not enough values to unpack (expected 5, got 4)"),+ ),+ pytest.raises(ValueError) as raised,+ ):+ source.get_schemas(_config(), team_id=1)++ _, is_expected_source_error = _classify_refresh_schemas_error(source, raised.value)+ assert is_expected_source_error is False+++def test_unrecognized_trino_discovery_failure_is_not_reported_as_a_posthog_exception() -> None:+ source = TrinoSource()++ _, is_expected_source_error = _classify_refresh_schemas_error(+ source, TrinoSchemaDiscoveryError("Query exceeded per-node memory limit")+ )++ assert is_expected_source_error is True++def test_connect_trino_closes_tracked_session_when_connect_fails() -> None:session = MagicMock()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.pyindex 4ff5a2873cec..357a8c920225 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py@@ -4,6 +4,8 @@ from collections.abc import Iteratorfrom contextlib import contextmanagerfrom typing import TYPE_CHECKING, Any+from requests.exceptions import RequestException+from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session@@ -18,6 +20,33 @@ TRINO_SYSTEM_SCHEMAS = ("information_schema",)TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR = ("Turn on TLS certificate verification to use password or JWT authentication.")+TRINO_AUTHENTICATION_ERROR = "Trino rejected the credentials. Check the username and authentication details."+TRINO_CATALOG_NOT_FOUND_ERROR = "Trino could not find that catalog. Check the catalog name and the user's permissions."+TRINO_ACCESS_DENIED_ERROR = (+ "Trino did not allow this user to read the requested data. "+ "Ask your Trino administrator for read access, then try again."+)+TRINO_ACCESS_CONTROL_UNAVAILABLE_ERROR = (+ "Trino's access control service did not answer, so Trino could not authorize the request. "+ "Try again, or ask your Trino administrator to check that service."+)+TRINO_TLS_CERTIFICATE_ERROR = (+ "PostHog could not verify the Trino server's TLS certificate. "+ "Check the certificate or turn off certificate verification."+)+TRINO_CONNECTION_ERROR = "PostHog could not connect to Trino."++# Every message `trino_error_to_message` produces for a recognized failure. The source lists them as+# its own error patterns, so the API shows the message instead of a generic one.+TRINO_KNOWN_ERROR_MESSAGES = (+ TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR,+ TRINO_AUTHENTICATION_ERROR,+ TRINO_CATALOG_NOT_FOUND_ERROR,+ TRINO_ACCESS_DENIED_ERROR,+ TRINO_ACCESS_CONTROL_UNAVAILABLE_ERROR,+ TRINO_TLS_CERTIFICATE_ERROR,+ TRINO_CONNECTION_ERROR,+)POSTHOG_MANAGED_TRINO_HOSTS = frozenset({"trino.dw.dev.postwh.com",@@ -45,18 +74,51 @@ class DiscoveredTrinoTable:columns: tuple[TrinoColumn, ...]+class TrinoSchemaDiscoveryError(Exception):+ """A failure Trino reported while PostHog listed the catalog's tables.++ The message is already worded for the person who connects the source.+ """+++class TrinoConfigurationError(ValueError):+ """A connection setting Trino cannot be reached with, found before PostHog opens the connection."""+++@contextmanager+def trino_failures_as_discovery_error() -> Iterator[None]:+ """Word a failed trip to Trino for the person who connects the source.++ A failure of PostHog's own code keeps its type, so error tracking still sees it.+ """+ from trino.exceptions import Error, HttpError # noqa: PLC0415 — keeps the optional driver off startup paths++ try:+ yield+ except (Error, HttpError, RequestException, TrinoConfigurationError) as exc:+ raise TrinoSchemaDiscoveryError(trino_error_to_message(exc)) from exc++def trino_error_to_message(error: Exception) -> str:message = str(error).strip()lowered = message.lower()if message == TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR:return message- if "authentication" in lowered or "unauthorized" in lowered or "401" in lowered:- return "Trino rejected the credentials. Check the username and authentication details."+ # Match the driver's HTTP 401 form ("error 401: ..."), not a bare "401": a Trino query error's+ # text carries a query ID whose time part can hold "401" and would derail this classification.+ if "authentication" in lowered or "unauthorized" in lowered or "error 401" in lowered:+ return TRINO_AUTHENTICATION_ERROR+ # Trino gives permission checks to an access control plugin. That plugin can fail on its own, for+ # example when it cannot reach its policy service, which nobody can fix from PostHog.+ if "opa backend" in lowered or "access control" in lowered:+ return TRINO_ACCESS_CONTROL_UNAVAILABLE_ERROR+ if "access denied" in lowered or "permission denied" in lowered or "not authorized" in lowered:+ return TRINO_ACCESS_DENIED_ERRORif "catalog" in lowered and ("not found" in lowered or "does not exist" in lowered):- return "Trino could not find that catalog. Check the catalog name and the user's permissions."+ return TRINO_CATALOG_NOT_FOUND_ERRORif "certificate" in lowered or "ssl" in lowered:- return "PostHog could not verify the Trino server's TLS certificate. Check the certificate or turn off certificate verification."- return message.splitlines()[0] if message else "PostHog could not connect to Trino."+ return TRINO_TLS_CERTIFICATE_ERROR+ return message.splitlines()[0] if message else TRINO_CONNECTION_ERRORdef _authentication(config: TrinoSourceConfig) -> Any:@@ -71,13 +133,13 @@ def _authentication(config: TrinoSourceConfig) -> Any:if selection == "password":if not config.auth_type.password:- raise ValueError("Password is required for password authentication.")+ raise TrinoConfigurationError("Password is required for password authentication.")return BasicAuthentication(config.auth_type.user, config.auth_type.password)if selection == "jwt":if not config.auth_type.token:- raise ValueError("Token is required for JWT authentication.")+ raise TrinoConfigurationError("Token is required for JWT authentication.")return JWTAuthentication(config.auth_type.token)- raise ValueError("Choose a supported Trino authentication type.")+ raise TrinoConfigurationError("Choose a supported Trino authentication type.")@contextmanager@@ -86,9 +148,9 @@ def connect_trino(config: TrinoSourceConfig) -> Iterator[Connection]:if config.auth_type.selection != "none":if not config.use_ssl:- raise ValueError("Password and JWT authentication require HTTPS.")+ raise TrinoConfigurationError("Password and JWT authentication require HTTPS.")if not config.verify_ssl:- raise ValueError(TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR)+ raise TrinoConfigurationError(TRINO_CREDENTIALS_REQUIRE_TLS_VERIFICATION_ERROR)redacted = tuple(value for value in (config.auth_type.password, config.auth_type.token) if isinstance(value, str) and value