Skip to content

: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.

fix(data-warehouse): bound connect and metadata waits in sql sources (#112672)

Tom Owerse72e17f5cf8f
diff --git a/products/warehouse_sources/backend/models/ssh_tunnel.py b/products/warehouse_sources/backend/models/ssh_tunnel.py
index b54e0fe2b683..5f9b32d328b1 100644
--- a/products/warehouse_sources/backend/models/ssh_tunnel.py
+++ b/products/warehouse_sources/backend/models/ssh_tunnel.py
@@ -1,4 +1,5 @@
import base64
+import socket
import typing
import dataclasses
from io import StringIO
@@ -6,8 +7,12 @@ from typing import IO, Literal
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import dsa, ec, ed25519, rsa
-from paramiko import DSSKey, ECDSAKey, Ed25519Key, PKey, RSAKey
-from sshtunnel import SSHTunnelForwarder
+from paramiko import DSSKey, ECDSAKey, Ed25519Key, PKey, RSAKey, Transport
+from sshtunnel import (
+ SSH_TIMEOUT,
+ BaseSSHTunnelForwarderError,
+ SSHTunnelForwarder as _UnboundedSSHTunnelForwarder,
+)
from posthog.dataclasses import frozen
@@ -35,6 +40,44 @@ _HOST_KEY_FORMAT_HELP = (
)
+# Limits on each step of the connection to the SSH server. paramiko opens the socket with no
+# timeout when it gets an address, so a server that drops packets holds the caller for as long as
+# the kernel keeps retrying. The other three are the paramiko defaults, set here so that a paramiko
+# upgrade cannot remove a limit without a change in this file.
+SSH_TUNNEL_CONNECT_TIMEOUT_SECONDS = 15
+SSH_TUNNEL_BANNER_TIMEOUT_SECONDS = 15
+SSH_TUNNEL_HANDSHAKE_TIMEOUT_SECONDS = 15
+SSH_TUNNEL_AUTH_TIMEOUT_SECONDS = 30
+
+# Starts with the wording sshtunnel uses for every other failure to reach the gateway. The sources
+# match that prefix to classify the error and to show the user how to fix the tunnel.
+SSH_TUNNEL_CONNECT_TIMEOUT_ERROR = (
+ "Could not establish session to SSH gateway: the SSH server did not accept a connection within "
+ f"{SSH_TUNNEL_CONNECT_TIMEOUT_SECONDS} seconds"
+)
+
+
+class SSHTunnelForwarder(_UnboundedSSHTunnelForwarder):
+ """An `sshtunnel` forwarder with a limit on every step of the connection to the SSH server."""
+
+ def _get_transport(self) -> Transport:
+ # The parent method also handles a proxy. Nothing here configures one, so this keeps only
+ # its direct path and its transport settings.
+ try:
+ sock = socket.create_connection((self.ssh_host, self.ssh_port), timeout=SSH_TUNNEL_CONNECT_TIMEOUT_SECONDS)
+ except TimeoutError as e:
+ raise BaseSSHTunnelForwarderError(SSH_TUNNEL_CONNECT_TIMEOUT_ERROR) from e
+ sock.settimeout(SSH_TIMEOUT)
+ transport = Transport(sock)
+ transport.banner_timeout = SSH_TUNNEL_BANNER_TIMEOUT_SECONDS
+ transport.handshake_timeout = SSH_TUNNEL_HANDSHAKE_TIMEOUT_SECONDS
+ transport.auth_timeout = SSH_TUNNEL_AUTH_TIMEOUT_SECONDS
+ transport.set_keepalive(self.set_keepalive)
+ transport.use_compression(compress=self.compression)
+ transport.daemon = self.daemon_transport
+ return transport
+
+
class HostKeyParseError(ValueError):
"""Carries the user-facing reason a pasted host key was rejected."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/discover_schemas_workflow.py b/products/warehouse_sources/backend/temporal/data_imports/discover_schemas_workflow.py
index d01ce160989e..bacfa5374494 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/discover_schemas_workflow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/discover_schemas_workflow.py
@@ -11,6 +11,10 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
sync_new_schemas_activity,
)
+# A source that puts a deadline on its own schema discovery keeps that deadline below this. The
+# source then fails with its own error, and the activity thread does not outlive the timeout.
+DISCOVER_SCHEMAS_ACTIVITY_TIMEOUT = dt.timedelta(minutes=10)
+
@workflow.defn(name="discover-schemas")
class DiscoverSchemasWorkflow(PostHogWorkflow):
@@ -33,7 +37,7 @@ class DiscoverSchemasWorkflow(PostHogWorkflow):
await workflow.execute_activity(
sync_new_schemas_activity,
inputs,
- start_to_close_timeout=dt.timedelta(minutes=10),
+ start_to_close_timeout=DISCOVER_SCHEMAS_ACTIVITY_TIMEOUT,
retry_policy=RetryPolicy(
initial_interval=dt.timedelta(seconds=10),
maximum_interval=dt.timedelta(seconds=60),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/deadline.py
new file mode 100644
index 000000000000..a93eaf034095
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/deadline.py
@@ -0,0 +1,48 @@
+import threading
+import contextvars
+from collections.abc import Callable
+from concurrent.futures import Future
+from typing import TypeVar
+
+from django.db import connections
+
+_T = TypeVar("_T")
+
+
+class DeadlineExceededError(Exception):
+ """The operation gave no answer before its deadline."""
+
+ def __init__(self, timeout_seconds: float) -> None:
+ super().__init__(f"No answer within {timeout_seconds:g} seconds")
+ self.timeout_seconds = timeout_seconds
+
+
+def run_with_deadline(operation: Callable[[], _T], *, timeout_seconds: float, thread_name: str) -> _T:
+ """Run `operation` and raise `DeadlineExceededError` if it gives no answer in time.
+
+ For a blocking call into a driver that has no timeout of its own. Python cannot stop a thread,
+ so the operation runs on a daemon thread and the caller stops waiting at the deadline. The
+ caller's thread then returns, which is what lets a Temporal activity finish and a worker shut
+ down. The abandoned thread ends when its call returns or when the process exits.
+
+ `operation` must own every resource it uses, because it can still be running after the caller
+ has moved on. Do not pass it a connection that the caller also uses.
+ """
+ outcome: Future[_T] = Future()
+ context = contextvars.copy_context()
+
+ def _run() -> None:
+ try:
+ outcome.set_result(context.run(operation))
+ except BaseException as e:
+ outcome.set_exception(e)
+ finally:
+ # Django connections are per thread, and nothing else closes the ones this thread opened.
+ connections.close_all()
+
+ thread = threading.Thread(target=_run, name=thread_name, daemon=True)
+ thread.start()
+ thread.join(timeout_seconds)
+ if not outcome.done():
+ raise DeadlineExceededError(timeout_seconds)
+ return outcome.result()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
index 561eebd563e9..d92160b2b0ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py
@@ -28,6 +28,10 @@ from posthog.utils import get_instance_region
from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel
from products.warehouse_sources.backend.models.util import _is_safe_public_ip
from products.warehouse_sources.backend.temporal.data_imports.sources.common.config import Config
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.deadline import (
+ DeadlineExceededError,
+ run_with_deadline,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
IntegrationAccount,
)
@@ -53,6 +57,9 @@ _NON_ASCII_HOST_ERROR = (
"This host has characters outside ASCII. Enter its punycode form instead, the spelling that starts with xn--."
)
+# The longest the host check waits for a DNS answer before it reports a temporary failure.
+HOST_RESOLUTION_TIMEOUT_SECONDS = 15
+
# The sync registry and the schema-refresh map match this prefix; the rest of the message carries
# the volatile host details.
DATABASE_HOST_NOT_ALLOWED_ERROR = "Database host not allowed"
@@ -190,8 +197,15 @@ def resolve_safe_host(host: str, team_id: int | None) -> HostResolution:
pass
try:
- addrinfo = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
+ addrinfo = run_with_deadline(
+ lambda: socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP),
+ timeout_seconds=HOST_RESOLUTION_TIMEOUT_SECONDS,
+ thread_name="host-check-resolve",
+ )
resolved_ips = [str(sockaddr[0]) for *_meta, sockaddr in addrinfo]
+ except DeadlineExceededError as e:
+ # A resolver that does not answer is a blip too, and `getaddrinfo` has no timeout of its own.
+ raise TemporaryHostResolutionError(host) from e
except socket.gaierror as e:
# A resolver blip is not a verdict on the host; refusing it would disable the schema.
if is_temporary_resolution_failure(e):
@@ -584,9 +598,8 @@ def _check_direct_host(config, team_id: int | None) -> None:
same either way; it only costs the internal-host exemption on entry points that don't carry a
team yet.
- The resolve inside `resolve_safe_host` is unbounded. A stalled resolver therefore hangs the
- activity until Temporal's `start_to_close_timeout` rather than failing fast and retryably.
- Bounding this one is the follow-up.
+ The resolve inside `resolve_safe_host` stops at `HOST_RESOLUTION_TIMEOUT_SECONDS`, so a stalled
+ resolver fails fast and retryably.
"""
_checked_connect_host(config.host, team_id, DATABASE_HOST_NOT_ALLOWED_ERROR)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
index af7b410c6eda..5b9173bfe9cf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py
@@ -1,4 +1,5 @@
import socket
+import threading
from dataclasses import dataclass, field
import pytest
@@ -157,6 +158,19 @@ class TestIsHostSafe(SimpleTestCase):
assert not valid
assert error is not None and "Try again" in error
+ @override_settings(CLOUD_DEPLOYMENT="US")
+ def test_a_resolver_that_does_not_answer_is_reported_as_try_again(self) -> None:
+ release = threading.Event()
+ try:
+ with (
+ patch(f"{_MIXINS_MODULE}.HOST_RESOLUTION_TIMEOUT_SECONDS", 0.05),
+ patch(f"{_MIXINS_MODULE}.socket.getaddrinfo", side_effect=lambda *args, **kwargs: release.wait()),
+ ):
+ with pytest.raises(TemporaryHostResolutionError):
+ resolve_safe_host("db.example.com", team_id=999)
+ finally:
+ release.set()
+
@override_settings(CLOUD_DEPLOYMENT="US")
def test_a_host_with_characters_outside_ascii_is_refused_before_any_lookup(self) -> None:
with patch(f"{_MIXINS_MODULE}.socket.getaddrinfo") as getaddrinfo_mock:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_deadline.py
new file mode 100644
index 000000000000..8c108efe9c52
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_deadline.py
@@ -0,0 +1,38 @@
+import threading
+import contextvars
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.deadline import (
+ DeadlineExceededError,
+ run_with_deadline,
+)
+
+_REQUEST_ID: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="unset")
+
+
+def test_returns_the_result_with_the_callers_context() -> None:
+ _REQUEST_ID.set("from-caller")
+
+ assert run_with_deadline(_REQUEST_ID.get, timeout_seconds=5, thread_name="t") == "from-caller"
+
+
+def test_raises_the_error_of_the_operation() -> None:
+ def _fail() -> None:
+ raise TimeoutError("driver timeout")
+
+ with pytest.raises(TimeoutError, match="driver timeout"):
+ run_with_deadline(_fail, timeout_seconds=5, thread_name="t")
+
+
+def test_an_operation_that_hangs_raises_at_the_deadline_and_does_not_hold_the_caller() -> None:
+ release = threading.Event()
+ try:
+ with pytest.raises(DeadlineExceededError) as error:
+ run_with_deadline(release.wait, timeout_seconds=0.05, thread_name="hung-driver-call")
+ finally:
+ release.set()
+
+ assert error.value.timeout_seconds == 0.05
+ abandoned = [thread for thread in threading.enumerate() if thread.name == "hung-driver-call"]
+ assert all(thread.daemon for thread in abandoned)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
index e3677c2ac003..605a0015552a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/mongo.py
@@ -23,7 +23,7 @@ from pymongo import ASCENDING, MongoClient
from pymongo.collection import Collection
from pymongo.cursor import Cursor
from pymongo.database import Database
-from pymongo.errors import CursorNotFound, OperationFailure, PyMongoError, ServerSelectionTimeoutError
+from pymongo.errors import CursorNotFound, ExecutionTimeout, OperationFailure, PyMongoError, ServerSelectionTimeoutError
from pymongo.server_description import ServerDescription
from structlog.types import FilteringBoundLogger
@@ -55,6 +55,12 @@ from products.warehouse_sources.backend.types import IncrementalFieldType, Parti
SCHEMA_INFERENCE_LIMIT = 10_000 # First 10k documents
SCHEMA_INFERENCE_TIMEOUT_MS = 45_000 # 45 seconds
+# Server-side limits (`maxTimeMS`) on the metadata commands that run before the first document is
+# read. The count runs the whole pipeline of a view, or scans a collection that has no index for
+# the filter, and each attempt of the import runs it again. Its result is only a progress estimate.
+ROW_COUNT_TIMEOUT_MS = 60_000
+COLLECTION_STATS_TIMEOUT_MS = 30_000
+
# Mongo yields whole documents (the full doc rides along under `data`), so a collection of large
# documents can OOM the worker when a chunk is materialised into a PyArrow table — before any Delta
# merge. Size the extraction chunk to a fixed byte budget: rows-per-chunk are derived from the average
@@ -381,7 +387,7 @@ def _get_partition_settings(
"""Get partition settings for given MongoDB collection."""
try:
# Get collection stats
- stats = collection.database.command("collStats", collection_name)
+ stats = collection.database.command("collStats", collection_name, maxTimeMS=COLLECTION_STATS_TIMEOUT_MS)
collection_size = stats.get("size", 0) # size in bytes
row_count = stats.get("count", 0)
@@ -618,7 +624,7 @@ def _get_avg_document_size(collection: Collection, logger: FilteringBoundLogger)
default chunk size. Never raises: chunk sizing is best-effort tuning, not correctness.
"""
try:
- stats = collection.database.command("collStats", collection.name)
+ stats = collection.database.command("collStats", collection.name, maxTimeMS=COLLECTION_STATS_TIMEOUT_MS)
avg_obj_size = stats.get("avgObjSize")
return int(avg_obj_size) if avg_obj_size else None
except _UNREACHABLE_CLUSTER_ERRORS:
@@ -628,13 +634,35 @@ def _get_avg_document_size(collection: Collection, logger: FilteringBoundLogger)
return None
+def _estimate_rows_to_sync(collection: Collection, query: dict[str, Any], logger: FilteringBoundLogger) -> int:
+ """Row estimate for a collection whose exact count ran past `ROW_COUNT_TIMEOUT_MS`.
+
+ The collection metadata holds a document count that costs no scan, but it counts the whole
+ collection, so it stands in only for an unfiltered read. A filtered read, and a view, which has
+ no such metadata, report 0. That is what a failed count reports too.
+ """
+ if not query:
+ try:
+ estimate = collection.estimated_document_count(maxTimeMS=COLLECTION_STATS_TIMEOUT_MS)
+ logger.debug(f"_get_rows_to_sync: count timed out, using estimate rows_to_sync={estimate}")
+ return estimate
+ except _UNREACHABLE_CLUSTER_ERRORS:
+ raise
+ except PyMongoError as e:
+ logger.debug(f"_get_rows_to_sync: count timed out and no estimate is available ({e})")
+ logger.warning(f"_get_rows_to_sync: the count did not finish in {ROW_COUNT_TIMEOUT_MS} ms. Using 0 as rows to sync")
+ return 0
+
+
def _get_rows_to_sync(collection: Collection, query: dict[str, Any], logger: FilteringBoundLogger) -> int:
try:
- rows_to_sync = collection.count_documents(query)
+ rows_to_sync = collection.count_documents(query, maxTimeMS=ROW_COUNT_TIMEOUT_MS)
logger.debug(f"_get_rows_to_sync: rows_to_sync={rows_to_sync}")
return rows_to_sync
except _UNREACHABLE_CLUSTER_ERRORS:
raise
+ except ExecutionTimeout:
+ return _estimate_rows_to_sync(collection, query, logger)
except PyMongoError as e:
# rows_to_sync is only a progress estimate, so a failed count degrades to 0
# rather than failing the sync. Connectivity/auth failures here are expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py
index f49f8152dea5..d21682227d70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mongodb/test_mongo.py
@@ -18,7 +18,7 @@ from bson.codec_options import CodecOptions
from bson.max_key import MaxKey
from bson.min_key import MinKey
from parameterized import parameterized
-from pymongo.errors import CursorNotFound, OperationFailure, ServerSelectionTimeoutError
+from pymongo.errors import CursorNotFound, ExecutionTimeout, OperationFailure, ServerSelectionTimeoutError
from pymongo.hello import Hello
from pymongo.server_description import ServerDescription
@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mo
MONGO_KEYS_UNAVAILABLE_ERROR,
MONGO_MAX_CHUNK_ROWS,
MONGO_MIN_CHUNK_ROWS,
+ ROW_COUNT_TIMEOUT_MS,
MongoResumeConfig,
_adaptive_chunk_size,
_build_query,
@@ -710,6 +711,28 @@ class TestGetRowsToSync(SimpleTestCase):
coll = MagicMock()
coll.count_documents.return_value = 42
assert _get_rows_to_sync(coll, {}, MagicMock()) == 42
+ coll.count_documents.assert_called_once_with({}, maxTimeMS=ROW_COUNT_TIMEOUT_MS)
+
+ @parameterized.expand(
+ [
+ ("unfiltered_read_uses_the_collection_estimate", {}, 1_000, None, 1_000),
+ ("filtered_read_has_no_estimate", {"updated_at": {"$gt": 5}}, 1_000, None, 0),
+ (
+ "view_has_no_estimate",
+ {},
+ None,
+ OperationFailure("Namespace db.orders_view is a view, not a collection"),
+ 0,
+ ),
+ ]
+ )
+ def test_count_past_the_time_limit_falls_back(self, _name, query, estimate, estimate_error, expected):
+ coll = MagicMock()
+ coll.count_documents.side_effect = ExecutionTimeout("operation exceeded time limit", code=50)
+ coll.estimated_document_count.return_value = estimate
+ coll.estimated_document_count.side_effect = estimate_error
+
+ assert _get_rows_to_sync(coll, query, MagicMock()) == expected
def test_pymongo_error_returns_zero_without_capture(self):
coll = MagicMock()
@@ -879,7 +902,7 @@ class _FakeCollection:
self.last_cursor = cursor
return cursor
- def count_documents(self, query: dict[str, Any]) -> int:
+ def count_documents(self, query: dict[str, Any], maxTimeMS: int | None = None) -> int:
return len(self._docs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
index 5bdce8e9f556..1af9e08bb457 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py
@@ -20,7 +20,9 @@ import pymssql
import structlog
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
+from posthog.temporal.common.errors import NonReportableError
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
DEFAULT_NUMERIC_PRECISION,
@@ -34,6 +36,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers
incremental_type_to_initial_value,
incremental_type_to_operator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.deadline import (
+ DeadlineExceededError,
+ run_with_deadline,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import open_ssh_tunnel
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
BracketIdentifierQuoter,
@@ -61,7 +67,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mssql import MSSQLSourceConfig
-from products.warehouse_sources.backend.types import IncrementalFieldType
+from products.warehouse_sources.backend.types import IncrementalFieldType, PartitionSettings
__all__ = [
"MSSQLColumn",
@@ -77,6 +83,44 @@ SYSTEM_MSSQL_SCHEMAS = ("sys", "guest", "INFORMATION_SCHEMA")
_T = TypeVar("_T")
+# FreeTDS applies this limit to the TCP connect and to the login.
+MSSQL_LOGIN_TIMEOUT_SECONDS = 5
+
+# The longest a metadata statement waits for a lock before SQL Server ends it with error 1222. The
+# catalog views wait behind a schema modification lock, so an open DDL transaction on the server
+# blocks them without limit. Set on the metadata connections only. The connection that reads the
+# rows keeps the server default.
+MSSQL_METADATA_LOCK_TIMEOUT_MS = 60_000
+
+# Client-side limits on the work that runs before the first row is read. pymssql has no limit that
+# can do this job: its `timeout` argument calls the DB-Library function `dbsettime`, which applies
+# to every connection in the process, so it would also end the row read of each other MSSQL import
+# on this worker. The work runs under `run_with_deadline` instead.
+#
+# Schema discovery must end before the 10 minute `start_to_close_timeout` of its Temporal activity.
+MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS = 300
+MSSQL_TABLE_SETUP_DEADLINE_SECONDS = 300
+MSSQL_ROW_COUNT_DEADLINE_SECONDS = 120
+
+# Stable prefix, matched by `MSSQLSource.get_non_retryable_errors`.
+MSSQL_METADATA_TIMEOUT_ERROR = "SQL Server did not answer in time"
+
+
+class MSSQLMetadataTimeoutError(NonReportableError):
+ """SQL Server gave no answer to the connect or to a metadata query before the deadline."""
+
+ def __init__(self, action: str, timeout_seconds: float) -> None:
+ super().__init__(f"{MSSQL_METADATA_TIMEOUT_ERROR} while PostHog {action} (waited {timeout_seconds:g} seconds)")
+
+
+def run_metadata_with_deadline(operation: Callable[[], _T], *, action: str, timeout_seconds: float) -> _T:
+ """Run connect-and-read metadata work, and raise `MSSQLMetadataTimeoutError` when it hangs."""
+ try:
+ return run_with_deadline(operation, timeout_seconds=timeout_seconds, thread_name="mssql-metadata")
+ except DeadlineExceededError as e:
+ raise MSSQLMetadataTimeoutError(action, timeout_seconds) from e
+
+
# DB-Lib error 20047 — "DBPROCESS is dead or not enabled". The TDS connection died mid-stream (an
# idle cull, a failover, a brief network blip), leaving pymssql's dbprocess dead so the in-flight
# fetch raises. A fresh connection recovers, so this is transient rather than a config error.
@@ -349,6 +393,18 @@ class MSSQLColumn(Column):
return pa.field(self.name, arrow_type, nullable=self.nullable)
+@frozen
+class MSSQLTableSetup:
+ """Everything `build_pipeline` learns about a table before it can stream rows."""
+
+ primary_keys: list[str] | None
+ projection: TableProjection[MSSQLColumn]
+ inner_query: str
+ inner_query_args: dict[str, Any]
+ chunk_size: int
+ partition_settings: PartitionSettings | None
+
+
class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Connection, pymssql.Cursor]): # ty: ignore[invalid-type-arguments]
"""MSSQL driver implementation paired with `MSSQLSource`.
@@ -365,11 +421,20 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
# ------------------------------------------------------------------
@contextmanager
- def connect(self, config: MSSQLSourceConfig, *, team_id: int | None = None) -> Iterator[pymssql.Connection]:
+ def connect(
+ self,
+ config: MSSQLSourceConfig,
+ *,
+ team_id: int | None = None,
+ lock_timeout_ms: int | None = MSSQL_METADATA_LOCK_TIMEOUT_MS,
+ ) -> Iterator[pymssql.Connection]:
"""Open a pymssql connection for the duration of the context.
Opens the SSH tunnel (if configured) once, then connects with the
- MSSQL-wide conventions: 5s login timeout.
+ MSSQL-wide conventions: `MSSQL_LOGIN_TIMEOUT_SECONDS` login timeout.
+
+ `lock_timeout_ms` limits how long each statement on this connection waits for a lock.
+ The default suits metadata work. Pass None for the connection that reads the rows.
The hostname goes to pymssql as is. `pymssql.connect` takes one `server`, which FreeTDS
uses both to dial and as the login server name, so there is no way to dial a pinned
@@ -384,8 +449,11 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
database=config.database,
user=config.user,
password=config.password,
- login_timeout=5,
+ login_timeout=MSSQL_LOGIN_TIMEOUT_SECONDS,
) as conn:
+ if lock_timeout_ms is not None:
+ with conn.cursor() as cursor:
+ cursor.execute(f"SET LOCK_TIMEOUT {int(lock_timeout_ms)}")
yield conn
@contextmanager
@@ -921,37 +989,74 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
incremental_field=incremental_field,
)
- with self.connect(config, team_id=inputs.team_id) as connection:
- with connection.cursor() as cursor:
- primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
- full_table = self.get_table_metadata(cursor, schema, table_name)
-
- # Resolve PKs before projection so SELECT and Arrow schema agree.
- if primary_keys is None and "id" in full_table:
- primary_keys = ["id"]
-
- setup_projection = _resolve_projection(full_table, primary_keys)
- logger.debug(f"Source schema: {setup_projection.table.to_arrow_schema()}")
-
- inner_query, inner_query_args = _build_query(
- schema,
- table_name,
- should_use_incremental_field,
- incremental_field,
- incremental_field_type,
- db_incremental_field_last_value,
- enabled_columns=setup_projection.enabled_columns,
- primary_keys=primary_keys,
- row_filters=row_filters,
- )
+ def _read_table_setup() -> MSSQLTableSetup:
+ with self.connect(config, team_id=inputs.team_id) as connection:
+ with connection.cursor() as cursor:
+ primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
+ full_table = self.get_table_metadata(cursor, schema, table_name)
- rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)
- chunk_size = self.get_chunk_size(cursor, schema, table_name, inner_query, inner_query_args, logger)
- partition_settings = (
- self.get_partition_settings(cursor, schema, table_name, logger)
- if should_use_incremental_field
- else None
- )
+ # Resolve PKs before projection so SELECT and Arrow schema agree.
+ if primary_keys is None and "id" in full_table:
+ primary_keys = ["id"]
+
+ projection = _resolve_projection(full_table, primary_keys)
+ logger.debug(f"Source schema: {projection.table.to_arrow_schema()}")
+
+ inner_query, inner_query_args = _build_query(
+ schema,
+ table_name,
+ should_use_incremental_field,
+ incremental_field,
+ incremental_field_type,
+ db_incremental_field_last_value,
+ enabled_columns=projection.enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=row_filters,
+ )
+
+ return MSSQLTableSetup(
+ primary_keys=primary_keys,
+ projection=projection,
+ inner_query=inner_query,
+ inner_query_args=inner_query_args,
+ chunk_size=self.get_chunk_size(
+ cursor, schema, table_name, inner_query, inner_query_args, logger
+ ),
+ partition_settings=(
+ self.get_partition_settings(cursor, schema, table_name, logger)
+ if should_use_incremental_field
+ else None
+ ),
+ )
+
+ setup = run_metadata_with_deadline(
+ _read_table_setup,
+ action="read the table's columns and keys",
+ timeout_seconds=MSSQL_TABLE_SETUP_DEADLINE_SECONDS,
+ )
+ primary_keys = setup.primary_keys
+ setup_projection = setup.projection
+
+ def _count_rows() -> int:
+ with self.connect(config, team_id=inputs.team_id) as connection:
+ with connection.cursor() as cursor:
+ return self.get_rows_to_sync(cursor, setup.inner_query, setup.inner_query_args, logger)
+
+ # The count is only a progress estimate, and on a large table without a useful index it can
+ # run for longer than the read itself. It has its own connection and deadline, so a slow
+ # count costs the estimate and not the import.
+ try:
+ rows_to_sync = run_with_deadline(
+ _count_rows, timeout_seconds=MSSQL_ROW_COUNT_DEADLINE_SECONDS, thread_name="mssql-row-count"
+ )
+ except DeadlineExceededError:
+ logger.debug("get_rows_to_sync: the count did not finish in time. Using 0 as rows to sync")
+ rows_to_sync = 0
+ except Exception as e:
+ # A fault on this connection is not a fault of the import. If it is a real one, the
+ # connection that reads the rows hits it too, and it is classified there.
+ logger.debug(f"get_rows_to_sync: could not open the count connection: {e}. Using 0 as rows to sync")
+ rows_to_sync = 0
def _refreshed_projection(connection: pymssql.Connection) -> TableProjection[MSSQLColumn]:
"""Re-read the catalog on the streaming connection, right before the read query.
@@ -969,7 +1074,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
def get_rows() -> Iterator[Any]:
binary_reporter = BinaryColumnReporter(logger)
- with self.connect(config, team_id=inputs.team_id) as streaming_connection:
+ with self.connect(config, team_id=inputs.team_id, lock_timeout_ms=None) as streaming_connection:
projection = _refreshed_projection(streaming_connection)
arrow_schema = projection.table.to_arrow_schema()
with streaming_connection.cursor() as cursor:
@@ -997,7 +1102,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
# the schema to what came back instead of failing the Arrow build.
read_schema = restrict_schema_to_columns(arrow_schema, column_names)
- for rows in fetch_row_batches(cursor.fetchmany, max_rows=chunk_size):
+ for rows in fetch_row_batches(cursor.fetchmany, max_rows=setup.chunk_size):
yield table_from_iterator(
(dict(zip(column_names, row)) for row in rows),
read_schema,
@@ -1009,7 +1114,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
name=location.response_name,
items=get_rows,
primary_keys=primary_keys,
- partition_count=partition_settings.partition_count if partition_settings else None,
- partition_size=partition_settings.partition_size if partition_settings else None,
+ partition_count=setup.partition_settings.partition_count if setup.partition_settings else None,
+ partition_size=setup.partition_settings.partition_size if setup.partition_settings else None,
rows_to_sync=rows_to_sync,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py
index 832d7d0a2a5e..aa29054b595b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py
@@ -25,8 +25,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.mssql.mssql import (
_SSH_HANDSHAKE_EOF_ERROR,
_TABLE_NOT_FOUND_ERROR,
+ MSSQL_METADATA_TIMEOUT_ERROR,
+ MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS,
MSSQLImplementation,
+ MSSQLMetadataTimeoutError,
retry_on_transient_connection_error,
+ run_metadata_with_deadline,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -89,6 +93,11 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase
# died between opening and the query running — just surfaced through a different
# internal code path. A fresh connection from the next Temporal retry resolves it.
"Not connected to any MS SQL server",
+ # SQL Server error 1222. A metadata statement waited longer than the `SET LOCK_TIMEOUT`
+ # that `MSSQLImplementation.connect` sets, because another session held a lock on the
+ # catalog or on the table. The lock belongs to the customer's own workload and goes
+ # away when that transaction ends.
+ "Lock request time out period exceeded",
}
def get_non_retryable_errors(self) -> dict[str, str | None]:
@@ -185,6 +194,12 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase
# (SQL Server error 208): the lookup returns an empty result set rather than erroring, so
# our own guard fires before the SELECT. The table is gone from the source, so retrying
# replays the identical empty lookup. Match the stable prefix, not the schema/table name.
+ # Raised by `run_metadata_with_deadline` when the connect or a metadata query gives no
+ # answer at all. The next attempt opens the same connection and waits the same time, so
+ # a retry inside the job only holds a worker for longer. `handle_non_retryable_error`
+ # still tries again on a few later runs before it gives up, which covers a server that
+ # was briefly unreachable.
+ MSSQL_METADATA_TIMEOUT_ERROR: "Your SQL Server did not answer PostHog's connection or metadata queries in time. Check that the server is running and reachable, including through the SSH tunnel if you use one, and that no long-running transaction is holding locks on the tables being synced.",
_TABLE_NOT_FOUND_ERROR: "One of the tables you're syncing no longer exists in your SQL Server — it was likely dropped or renamed after it was first discovered. Remove it from the sync or restore it at the source, then re-enable the sync.",
}
@@ -212,7 +227,11 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase
api_version=api_version,
)
- return retry_on_transient_connection_error(discover)
+ return run_metadata_with_deadline(
+ lambda: retry_on_transient_connection_error(discover),
+ action="listed the tables",
+ timeout_seconds=MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS,
+ )
@property
def get_source_config(self) -> SourceConfig:
@@ -313,6 +332,8 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase
try:
self.get_schemas(config, team_id, api_version=api_version)
+ except MSSQLMetadataTimeoutError:
+ return False, _CONNECTION_TIMED_OUT_ERROR
except (HostNotAllowedError, TemporaryHostResolutionError) as e:
# The host policy refused the host, or its lookup never answered. Both carry their own
# user-facing wording and neither is a PostHog defect, so they are not captured.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py
index 172a74134122..b106968c02c1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py
@@ -1,8 +1,14 @@
+import threading
+
import pytest
from unittest.mock import MagicMock
import pymssql
+from products.warehouse_sources.backend.temporal.data_imports.discover_schemas_workflow import (
+ DISCOVER_SCHEMAS_ACTIVITY_TIMEOUT,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import Table, TableStats
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ColumnTypeCategory,
@@ -12,8 +18,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mssql import MSSQLSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.mssql.mssql import (
_SSH_HANDSHAKE_EOF_ERROR,
+ MSSQL_LOGIN_TIMEOUT_SECONDS,
+ MSSQL_METADATA_LOCK_TIMEOUT_MS,
+ MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS,
MSSQLColumn,
MSSQLImplementation,
+ MSSQLMetadataTimeoutError,
_build_query,
_is_deadlock_victim_error,
_is_transient_connection_error,
@@ -27,6 +37,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mssql.sour
)
from products.warehouse_sources.backend.types import IncrementalFieldType
+_MSSQL_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.mssql.mssql"
+
def _make_config(**overrides) -> MSSQLSourceConfig:
defaults: dict = {
@@ -603,10 +615,70 @@ class TestBuildPipeline:
def test_streams_through_separate_connection(self, build_pipeline_mocks):
mock_connect, streaming_cursor = build_pipeline_mocks
_drain_source()
- # Two connect calls: one for metadata, one for streaming.
- assert mock_connect.call_count == 2
+ # Three connect calls: one for metadata, one for the row count, one for streaming.
+ assert mock_connect.call_count == 3
assert streaming_cursor.execute.called
+ def test_setup_that_hangs_at_connect_raises_a_non_retryable_timeout(self, build_pipeline_mocks, mocker):
+ mock_connect, _ = build_pipeline_mocks
+ release = threading.Event()
+ mock_connect.side_effect = lambda **kwargs: release.wait()
+ mocker.patch(f"{_MSSQL_MODULE}.MSSQL_TABLE_SETUP_DEADLINE_SECONDS", 0.05)
+
+ try:
+ with pytest.raises(MSSQLMetadataTimeoutError) as error:
+ MSSQLImplementation().build_pipeline(_make_config(), _make_inputs())
+ finally:
+ release.set()
+
+ assert error_message_matches(str(error.value), MSSQLSource().get_non_retryable_errors())
+
+ @pytest.mark.parametrize("fails", [False, True], ids=["count_hangs", "count_connection_fails"])
+ def test_row_count_fault_costs_the_estimate_and_not_the_import(self, build_pipeline_mocks, mocker, fails):
+ release = threading.Event()
+
+ def _count(*args):
+ if fails:
+ raise pymssql.OperationalError(20009, b"Adaptive Server is unavailable or does not exist")
+ release.wait()
+
+ mocker.patch.object(MSSQLImplementation, "get_rows_to_sync", side_effect=_count)
+ mocker.patch(f"{_MSSQL_MODULE}.MSSQL_ROW_COUNT_DEADLINE_SECONDS", 0.05)
+
+ try:
+ source = MSSQLImplementation().build_pipeline(_make_config(), _make_inputs())
+ finally:
+ release.set()
+
+ assert source.rows_to_sync == 0
+
+
+class TestConnectTimeouts:
+ @pytest.mark.parametrize(
+ "connect_kwargs, expected_statements",
+ [
+ ({}, [f"SET LOCK_TIMEOUT {MSSQL_METADATA_LOCK_TIMEOUT_MS}"]),
+ ({"lock_timeout_ms": None}, []),
+ ],
+ ids=["metadata_connection", "row_reading_connection"],
+ )
+ def test_connect_limits_the_login_and_the_lock_wait_but_not_the_query(
+ self, mocker, connect_kwargs, expected_statements
+ ):
+ mocker.patch(f"{_MSSQL_MODULE}.open_ssh_tunnel").return_value.__enter__.return_value = ("localhost", 1433)
+ connection = MagicMock()
+ connection.__enter__.return_value = connection
+ cursor = connection.cursor.return_value.__enter__.return_value
+ mock_connect = mocker.patch(f"{_MSSQL_MODULE}.pymssql.connect", return_value=connection)
+
+ with MSSQLImplementation().connect(_make_config(), **connect_kwargs):
+ pass
+
+ assert mock_connect.call_args.kwargs["login_timeout"] == MSSQL_LOGIN_TIMEOUT_SECONDS
+ # pymssql applies `timeout` to every connection in the process, the row reads included.
+ assert "timeout" not in mock_connect.call_args.kwargs
+ assert [call.args[0] for call in cursor.execute.call_args_list] == expected_statements
+
class _RaisingTunnel:
"""Context manager whose `__enter__` raises, standing in for paramiko's handshake EOFError."""
@@ -812,6 +884,7 @@ class TestMSSQLSourceRetryableErrors:
@pytest.mark.parametrize(
"error",
[
+ pymssql.OperationalError(1222, b"Lock request time out period exceeded."),
# Real pymssql shape: DB-Lib error 20017 carried as (code, bytes) args.
pymssql.OperationalError(
20017, b"DB-Lib error message 20017, severity 9:\nUnexpected EOF from the server\n"
@@ -951,6 +1024,27 @@ class TestRetryOnTransientConnectionError:
assert operation.call_count == 3
+class TestGetSchemasDeadline:
+ def test_discovery_that_hangs_raises_before_the_activity_timeout(self, mocker):
+ release = threading.Event()
+ mocker.patch(f"{_MSSQL_MODULE}.open_ssh_tunnel").return_value.__enter__.return_value = ("localhost", 1433)
+ mocker.patch(f"{_MSSQL_MODULE}.pymssql.connect", side_effect=lambda **kwargs: release.wait())
+ mocker.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mssql.source"
+ ".MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS",
+ 0.05,
+ )
+
+ try:
+ with pytest.raises(MSSQLMetadataTimeoutError, match="SQL Server did not answer in time"):
+ MSSQLSource().get_schemas(_make_config(), team_id=1)
+ finally:
+ release.set()
+
+ def test_discovery_deadline_is_inside_the_activity_timeout(self):
+ assert MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS < DISCOVER_SCHEMAS_ACTIVITY_TIMEOUT.total_seconds()
+
+
class TestGetSchemasRetriesTransientDrop:
def test_get_schemas_retries_then_recovers(self, mocker):
# A transient DBPROCESS death mid-discovery must retry the whole connect-and-discover cycle
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
index 3bd286d45a89..0959553f5271 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py
@@ -118,6 +118,12 @@ _QUERY_BUILDER = SelectQueryBuilder(quoter=_IDENTIFIER_QUOTER)
# net_write_timeout / net_read_timeout — PyMySQL and MySQL both take seconds.
STATEMENT_TIMEOUT_SECONDS = 600 # 10 mins
+# Client-side PyMySQL read_timeout for a connection that reads metadata: schema discovery and the
+# setup work before the first row. Without it a server that stops answering holds the caller for
+# as long as the socket stays open. Schema discovery must also end before the 10 minute
+# `start_to_close_timeout` of its Temporal activity.
+METADATA_READ_TIMEOUT_SECONDS = 300
+
# pymysql error code for "Lost connection to MySQL server during query" — the
# symptom we see when the optimizer picks a bad plan (full scan + filesort) and
# the filesort preparation exceeds a middlebox / server-side query timeout
@@ -1171,7 +1177,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
self,
config: MySQLSourceConfig,
*,
- read_timeout: int | None = None,
+ read_timeout: int | None = METADATA_READ_TIMEOUT_SECONDS,
autocommit: bool = False,
team_id: int | None = None,
) -> Iterator[pymysql.Connection]:
@@ -1181,6 +1187,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
MySQL-wide conventions: safe date/datetime converters, and a
PlanetScale workload hint injected automatically when the host
resolves to a `*.psdb.cloud` address. Callers vary two things —
+ metadata work keeps the default `METADATA_READ_TIMEOUT_SECONDS`,
the streaming path sets `read_timeout=STATEMENT_TIMEOUT_SECONDS`
so multi-GB filesorts don't drop on middlebox timeouts before the
first rows are ready, and the keyset path sets `autocommit` so each
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
index 56ff956e151c..75b7564049a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py
@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq
_MAX_CONNECT_ATTEMPTS,
_MYSQL_SAFE_CONVERSIONS,
_SSH_HANDSHAKE_EOF_ERROR,
+ METADATA_READ_TIMEOUT_SECONDS,
STATEMENT_TIMEOUT_SECONDS,
UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR,
MySQLColumn,
@@ -1036,6 +1037,11 @@ class TestStreamingConnectionTimeouts:
streaming_kwargs = mock_connect.call_args_list[1].kwargs
assert streaming_kwargs["read_timeout"] == STATEMENT_TIMEOUT_SECONDS
+ def test_metadata_connection_has_a_read_timeout(self, build_pipeline_mocks):
+ mock_connect, _, _ = build_pipeline_mocks
+ _drain_source()
+ assert mock_connect.call_args_list[0].kwargs["read_timeout"] == METADATA_READ_TIMEOUT_SECONDS
+
def test_set_session_timeouts_are_executed(self, build_pipeline_mocks):
_, setup_cursor, _ = build_pipeline_mocks
_drain_source()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/client_deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/client_deadline.py
new file mode 100644
index 000000000000..2620040ba6f3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/client_deadline.py
@@ -0,0 +1,113 @@
+"""Client-side statement deadline for psycopg connections.
+
+`statement_timeout` is the server's limit, and it does not always apply. A transaction-mode pooler
+can run the `SET` on one backend and the next statement on another, some Postgres-compatible
+engines reject the setting, and a server that stops answering never reports a timeout at all. The
+deadline here is measured on the client, so it holds in each of those cases.
+"""
+
+import os
+import socket
+import threading
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Any, Self
+
+import psycopg
+import structlog
+from psycopg.abc import Params, Query
+
+logger = structlog.get_logger(__name__)
+
+# How long the cancel request itself can take.
+CANCEL_REQUEST_TIMEOUT_SECONDS = 10
+# How long the statement gets to end after the cancel request, before the socket is shut down.
+CANCEL_GRACE_SECONDS = 20
+
+
+class _StatementWatchdog:
+ def __init__(self, connection: psycopg.Connection[Any], timeout_seconds: float) -> None:
+ self._connection = connection
+ self._timeout_seconds = timeout_seconds
+ self._lock = threading.Lock()
+ self._finished = threading.Event()
+ self._timer = threading.Timer(timeout_seconds, self._expire)
+ self._timer.daemon = True
+
+ def start(self) -> None:
+ self._timer.start()
+
+ def finish(self) -> None:
+ self._timer.cancel()
+ # Waits for a cancel request that is in flight. A request that reached the server after
+ # this returned could cancel the next statement on the connection instead.
+ with self._lock:
+ self._finished.set()
+
+ def _expire(self) -> None:
+ with self._lock:
+ if self._finished.is_set():
+ return
+ logger.warning("data_imports.postgres_client_deadline", timeout_seconds=self._timeout_seconds)
+ try:
+ self._connection.cancel_safe(timeout=CANCEL_REQUEST_TIMEOUT_SECONDS)
+ except Exception as e:
+ logger.debug("data_imports.postgres_client_deadline_cancel_failed", error=str(e)[:200])
+
+ if self._finished.wait(CANCEL_GRACE_SECONDS):
+ return
+
+ # The server did not act on the cancel request. A closed socket makes the blocked read
+ # fail, which the callers handle as a dropped connection.
+ with self._lock:
+ if self._finished.is_set():
+ return
+ _shut_down_socket(self._connection)
+
+
+def _shut_down_socket(connection: psycopg.Connection[Any]) -> None:
+ try:
+ # A duplicate, so that closing it here leaves the descriptor that libpq owns open.
+ sock = socket.socket(fileno=os.dup(connection.fileno()))
+ except Exception as e:
+ logger.debug("data_imports.postgres_client_deadline_shutdown_failed", error=str(e)[:200])
+ return
+ try:
+ sock.shutdown(socket.SHUT_RDWR)
+ except OSError as e:
+ logger.debug("data_imports.postgres_client_deadline_shutdown_failed", error=str(e)[:200])
+ finally:
+ sock.close()
+
+
+@contextmanager
+def client_side_deadline(connection: psycopg.Connection[Any], timeout_seconds: float) -> Iterator[None]:
+ """End the statement that runs inside the block when it takes longer than `timeout_seconds`.
+
+ At the deadline the statement gets a cancel request, and raises `QueryCanceled`. If it is still
+ running `CANCEL_GRACE_SECONDS` later, the socket is shut down, and it raises `OperationalError`.
+ """
+ watchdog = _StatementWatchdog(connection, timeout_seconds)
+ watchdog.start()
+ try:
+ yield
+ finally:
+ watchdog.finish()
+
+
+def deadline_cursor_factory(timeout_seconds: float) -> type[psycopg.Cursor[Any]]:
+ """Return a cursor class that puts `client_side_deadline` on every `execute`."""
+
+ class DeadlineCursor(psycopg.Cursor[Any]):
+ def execute(
+ self,
+ query: Query,
+ params: Params | None = None,
+ *,
+ prepare: bool | None = None,
+ binary: bool | None = None,
+ ) -> Self:
+ with client_side_deadline(self.connection, timeout_seconds):
+ return super().execute(query, params, prepare=prepare, binary=binary)
+
+ return DeadlineCursor
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index e6cd91a49dce..34f98278e8d1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -97,6 +97,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (
PostgresSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.client_deadline import (
+ client_side_deadline,
+ deadline_cursor_factory,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import XminUnsupportedError
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.partitioned_tables import (
build_partition_query,
@@ -124,6 +128,14 @@ SYNC_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins
METADATA_STATEMENT_TIMEOUT_MS = 1000 * 60 * 10 # 10 mins
+# Client-side limit on each statement of the setup phase, which runs before the first row is read.
+# It sits one minute above the server limit, so it acts only when the server limit did not. See
+# `client_deadline` for the cases where that happens.
+SETUP_STATEMENT_CLIENT_DEADLINE_SECONDS = METADATA_STATEMENT_TIMEOUT_MS / 1000 + 60
+# `EXPLAIN` only plans the query, so one that is still running after this long waits on a lock or on
+# a server that stopped answering. The plan goes to a debug log line and nothing else needs it.
+EXPLAIN_CLIENT_DEADLINE_SECONDS = 60
+
# Rows the row-size probe aims to measure. Enough for a stable p95 and a meaningful widest row,
# few enough that `octet_length(t::text)` — which de-toasts every value — stays cheap on a table
# whose values are megabytes each.
@@ -2566,7 +2578,8 @@ def _explain_query(cursor: psycopg.Cursor, query: sql.Composed, logger: Filterin
# Debug-only, best-effort: EXPLAIN may use syntax the source rejects (e.g. TABLESAMPLE
# on CockroachDB), so swallow failures.
query_with_explain = sql.SQL("EXPLAIN {}").format(query)
- cursor.execute(query_with_explain)
+ with client_side_deadline(cursor.connection, EXPLAIN_CLIENT_DEADLINE_SECONDS):
+ cursor.execute(query_with_explain)
rows = cursor.fetchall()
explain_result: str = ""
# Build up a single string of the EXPLAIN output
@@ -3618,6 +3631,7 @@ def postgres_source(
# read-replica recovery conflict on a slow COUNT(*), or syntax the source rejects like
# TABLESAMPLE on CockroachDB — can't poison the rest. Replaces the per-probe savepoints.
conn.autocommit = True
+ conn.cursor_factory = deadline_cursor_factory(SETUP_STATEMENT_CLIENT_DEADLINE_SECONDS)
return conn
# A hot-standby recovery conflict ("conflict with recovery") cancels or terminates the probe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_client_deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_client_deadline.py
new file mode 100644
index 000000000000..bdf5903403bd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_client_deadline.py
@@ -0,0 +1,54 @@
+import socket
+import threading
+
+import pytest
+from unittest.mock import MagicMock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres import client_deadline
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.client_deadline import (
+ client_side_deadline,
+)
+
+
+def test_a_statement_that_ends_in_time_is_not_cancelled() -> None:
+ connection = MagicMock()
+
+ with client_side_deadline(connection, timeout_seconds=30):
+ pass
+
+ connection.cancel_safe.assert_not_called()
+
+
+def test_a_statement_past_the_deadline_gets_a_cancel_request() -> None:
+ cancelled = threading.Event()
+ connection = MagicMock()
+ connection.cancel_safe.side_effect = lambda timeout: cancelled.set()
+
+ with client_side_deadline(connection, timeout_seconds=0.01):
+ assert cancelled.wait(5)
+
+ connection.cancel_safe.assert_called_once_with(timeout=client_deadline.CANCEL_REQUEST_TIMEOUT_SECONDS)
+
+
+ "cancel_error",
+ [None, RuntimeError("cancel request refused")],
+ ids=["cancel_ignored_by_server", "cancel_request_fails"],
+)
+def test_a_statement_that_ignores_the_cancel_request_loses_its_socket(
+ monkeypatch: pytest.MonkeyPatch, cancel_error: Exception | None
+) -> None:
+ monkeypatch.setattr(client_deadline, "CANCEL_GRACE_SECONDS", 0.01)
+ client_end, server_end = socket.socketpair()
+ client_end.settimeout(5)
+ connection = MagicMock()
+ connection.fileno.return_value = client_end.fileno()
+ connection.cancel_safe.side_effect = cancel_error
+
+ try:
+ with client_side_deadline(connection, timeout_seconds=0.01):
+ # A blocked read on the socket of the connection, as in a statement the server never answers.
+ assert client_end.recv(1) == b""
+ finally:
+ client_end.close()
+ server_end.close()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index 996e3e349beb..38c4a2bd31c6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -113,6 +113,12 @@ __all__ = [
# keepalives a dead peer is detected in ~30-60s and raised as a fast,
# retryable `OperationalError` instead. These only fire when the peer stops
# responding, so they never interrupt a healthy long-running streaming sync.
+# Session statement timeout for a connection that reads metadata. The keepalives below end a query
+# whose peer went away. This ends a catalog query that the cluster accepts and then never answers,
+# for example one that waits behind a lock. Schema discovery must end before the 10 minute
+# `start_to_close_timeout` of its Temporal activity.
+METADATA_STATEMENT_TIMEOUT_MS = 1000 * 60 * 5
+
_REDSHIFT_CONNECT_OPTS: dict[str, Any] = {
"sslmode": "require",
"connect_timeout": 15,
@@ -576,6 +582,22 @@ def _rollback_if_aborted(connection: psycopg.Connection) -> None:
connection.rollback()
+def _set_session_statement_timeout(connection: psycopg.Connection, timeout_ms: int) -> None:
+ """Set the session statement timeout on a new connection.
+
+ Commits, because a `SET` is undone when its transaction rolls back, and because the callers
+ switch the connection to autocommit, which psycopg refuses inside a transaction. Best-effort:
+ a cluster that rejects the setting keeps its own default.
+ """
+ try:
+ connection.execute(sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(timeout_ms)))
+ connection.commit()
+ except psycopg.Error as e:
+ if _is_transient_connection_drop_error(e):
+ raise
+ _rollback_if_aborted(connection)
+
+
def _recover_after_failed_probe(connection: psycopg.Connection) -> None:
"""Roll back a best-effort probe's aborted transaction, swallowing a lost connection."""
try:
@@ -975,7 +997,13 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
# ------------------------------------------------------------------
@contextmanager
- def connect(self, config: RedshiftSourceConfig, *, team_id: int | None = None) -> Iterator[psycopg.Connection]:
+ def connect(
+ self,
+ config: RedshiftSourceConfig,
+ *,
+ team_id: int | None = None,
+ statement_timeout_ms: int | None = METADATA_STATEMENT_TIMEOUT_MS,
+ ) -> Iterator[psycopg.Connection]:
"""Open a psycopg connection for the duration of the context.
Opens the SSH tunnel (if configured) and connects with the
@@ -986,6 +1014,9 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
Redshift speaks the Postgres wire protocol through the same libpq, so it dials the
addresses it validated the same way: `pinned_host_kwargs` resolves the host once, checks
that answer against the host policy, and pins it through the `host`/`hostaddr` pair.
+
+ `statement_timeout_ms` is the session statement timeout. The default suits metadata work.
+ Pass None for the connection that reads the rows.
"""
with open_ssh_tunnel(config, team_id) as (host, port):
connect_kwargs: dict[str, Any] = {
@@ -1002,6 +1033,8 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
conn.adapters.register_loader("date", SafeDateLoader)
conn.adapters.register_loader("timestamp", SafeTimestampLoader)
conn.adapters.register_loader("timestamptz", SafeTimestamptzLoader)
+ if statement_timeout_ms is not None:
+ _set_session_statement_timeout(conn, statement_timeout_ms)
yield conn
# ------------------------------------------------------------------
@@ -2038,7 +2071,10 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
# yet. `ExitStack.enter_context` only registers cleanup after `__enter__` succeeds,
# so a failed attempt leaves nothing to tear down and the next attempt opens clean.
streaming_connection = _retry_on_transient_connection_drop(
- lambda: stack.enter_context(self.connect(config, team_id=inputs.team_id)), logger
+ lambda: stack.enter_context(
+ self.connect(config, team_id=inputs.team_id, statement_timeout_ms=None)
+ ),
+ logger,
)
streaming_connection.adapters.register_loader("json", JsonAsStringLoader)
projection = _refreshed_projection(streaming_connection)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
index 15647d8dc320..b20a3d4208fa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
RedshiftSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift import (
+ METADATA_STATEMENT_TIMEOUT_MS,
REDSHIFT_SINGLE_NODE_FETCH_LIMIT,
RedshiftColumn,
RedshiftImplementation,
@@ -1959,6 +1960,32 @@ class TestConnect:
assert kwargs["keepalives_count"] == 3
assert kwargs["tcp_user_timeout"] == 60000
+ @pytest.mark.parametrize(
+ "connect_kwargs, expected_statements",
+ [
+ ({}, [f"SET statement_timeout = {METADATA_STATEMENT_TIMEOUT_MS}"]),
+ ({"statement_timeout_ms": None}, []),
+ ],
+ ids=["metadata_connection", "row_reading_connection"],
+ )
+ def test_connect_sets_a_statement_timeout_for_metadata_only(self, mocker, connect_kwargs, expected_statements):
+ mocker.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.open_ssh_tunnel",
+ ).return_value.__enter__.return_value = ("localhost", 5439)
+ mock_conn = MagicMock()
+ mock_conn.__enter__.return_value = mock_conn
+ mocker.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.psycopg.connect",
+ return_value=mock_conn,
+ )
+
+ with RedshiftImplementation().connect(_make_config(), **connect_kwargs):
+ pass
+
+ assert [call.args[0].as_string() for call in mock_conn.execute.call_args_list] == expected_statements
+ # A `SET` that is not committed is undone by the first rollback.
+ assert mock_conn.commit.call_count == len(expected_statements)
+
def test_connect_registers_safe_date_and_timestamp_loaders(self, mocker):
# Wiring guard: these loaders only protect a sync if they're actually registered on the
# connection every `connect()` call produces.
diff --git a/products/warehouse_sources/backend/tests/test_ssh_tunnel.py b/products/warehouse_sources/backend/tests/test_ssh_tunnel.py
index 008dc53611c4..6ee1a0c2b5ee 100644
--- a/products/warehouse_sources/backend/tests/test_ssh_tunnel.py
+++ b/products/warehouse_sources/backend/tests/test_ssh_tunnel.py
@@ -1,9 +1,12 @@
import pytest
+from unittest.mock import MagicMock, patch
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519, rsa
from paramiko import RSAKey
+from sshtunnel import BaseSSHTunnelForwarderError
+from products.warehouse_sources.backend.models import ssh_tunnel as ssh_tunnel_module
from products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel, SSHTunnelConfig
@@ -251,6 +254,33 @@ def test_get_tunnel_pins_host_key(key_type, hostname):
assert forwarder.ssh_host_key == parsed
+def test_gateway_connect_that_hangs_raises_the_gateway_error():
+ forwarder = _password_tunnel(host_key=None).get_tunnel("host.com", 3306, ssh_host="93.184.216.34")
+
+ with patch.object(ssh_tunnel_module.socket, "create_connection", side_effect=TimeoutError("timed out")) as dial:
+ with pytest.raises(BaseSSHTunnelForwarderError, match="Could not establish session to SSH gateway"):
+ forwarder.start()
+
+ dial.assert_called_once_with(("93.184.216.34", 5432), timeout=ssh_tunnel_module.SSH_TUNNEL_CONNECT_TIMEOUT_SECONDS)
+
+
+def test_gateway_transport_limits_every_step_of_the_handshake():
+ forwarder = _password_tunnel(host_key=None).get_tunnel("host.com", 3306, ssh_host="93.184.216.34")
+
+ with (
+ patch.object(ssh_tunnel_module.socket, "create_connection", return_value=MagicMock()),
+ patch.object(ssh_tunnel_module, "Transport") as transport_class,
+ ):
+ transport = forwarder._get_transport()
+
+ assert transport is transport_class.return_value
+ assert (transport.banner_timeout, transport.handshake_timeout, transport.auth_timeout) == (
+ ssh_tunnel_module.SSH_TUNNEL_BANNER_TIMEOUT_SECONDS,
+ ssh_tunnel_module.SSH_TUNNEL_HANDSHAKE_TIMEOUT_SECONDS,
+ ssh_tunnel_module.SSH_TUNNEL_AUTH_TIMEOUT_SECONDS,
+ )
+
+
def test_get_tunnel_invalid_auth():
ssh_tunnel = SSHTunnel(
enabled=True,