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): limit silent waits in bigquery, redshift, mongodb and snowflake (#113672)

Tom Owersc5bcf666ad6c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
index f3e3f1da9ce9..aa28082cc021 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
@@ -13,9 +13,11 @@ from __future__ import annotations
import math
import time
import typing
+import threading
import contextlib
import collections
import collections.abc
+import concurrent.futures
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import date, datetime
@@ -333,6 +335,122 @@ def _query_should_retry(exc: Exception) -> bool:
)
+# Limits on the waits of one import. The BigQuery client passes `timeout=None` to its HTTP session
+# by default, and a streaming read has no limit between two pages, so without these a connection
+# that goes silent holds its worker until the activity ends.
+#
+# Each REST request, as (connect, read) seconds. The read limit is on one silent socket read, and
+# the server answers a wait for a query job every few seconds, so a job that runs for a long time
+# never reaches it.
+BIGQUERY_HTTP_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 120.0)
+# The exact count of a filtered read. Its result feeds the progress display and the billing limit
+# check only, so a count that is not done by this time gives 0 (unknown).
+BIGQUERY_ROW_COUNT_JOB_TIMEOUT_SECONDS = 120
+# The query job that copies the rows to a temporary table before the first row is read. It sorts
+# the full result of an incremental read, so it gets a long limit.
+BIGQUERY_COPY_JOB_TIMEOUT_SECONDS = 2 * 60 * 60
+# The wait for one page of the Storage Read API stream. A read that keeps returning pages starts
+# a new wait with each page.
+BIGQUERY_READ_ROWS_IDLE_TIMEOUT_SECONDS = 10 * 60
+
+# HTTP/2 keepalive pings let gRPC find a connection that a proxy or NAT dropped without a reset.
+_BIGQUERY_STORAGE_KEEPALIVE_OPTIONS: tuple[tuple[str, int], ...] = (
+ ("grpc.keepalive_time_ms", 60 * 1000),
+ ("grpc.keepalive_timeout_ms", 20 * 1000),
+ ("grpc.keepalive_permit_without_calls", 0),
+)
+
+# Stable prefixes, matched by `BigQuerySource.get_retryable_errors`.
+BIGQUERY_JOB_TIMEOUT_ERROR = "BigQuery did not finish the query job"
+BIGQUERY_READ_TIMEOUT_ERROR = "BigQuery sent no rows"
+
+
+class BigQueryJobTimeoutError(Exception):
+ """A query job was not done at its limit. A later attempt can succeed."""
+
+ def __init__(self, timeout_seconds: float) -> None:
+ super().__init__(f"{BIGQUERY_JOB_TIMEOUT_ERROR} within {timeout_seconds:g} seconds, so PostHog ended it")
+
+
+class BigQueryReadTimeoutError(Exception):
+ """The Storage Read API stream sent no page before the limit. A later attempt can succeed."""
+
+ def __init__(self, timeout_seconds: float) -> None:
+ super().__init__(f"{BIGQUERY_READ_TIMEOUT_ERROR} for {timeout_seconds:g} seconds, so PostHog ended the read")
+
+
+class _DeadlineAuthorizedSession(AuthorizedSession):
+ """An authorized session whose requests always have a timeout.
+
+ A default on the session is not sufficient, because the BigQuery client passes an explicit
+ `timeout=None` for each call that the caller gave no timeout.
+ """
+
+ def request( # type: ignore[override]
+ self,
+ method: str,
+ url: str,
+ data: Any = None,
+ headers: Any = None,
+ max_allowed_time: float | None = None,
+ timeout: Any = None,
+ **kwargs: Any,
+ ) -> Any:
+ return super().request(
+ method,
+ url,
+ data=data,
+ headers=headers,
+ max_allowed_time=max_allowed_time,
+ timeout=BIGQUERY_HTTP_TIMEOUT_SECONDS if timeout is None else timeout,
+ **kwargs,
+ )
+
+
+def _wait_for_job(job: Any, *, timeout_seconds: float, **result_kwargs: Any) -> Any:
+ """Wait for a query job, and raise `BigQueryJobTimeoutError` when it is not done in time."""
+ try:
+ return job.result(timeout=timeout_seconds, **result_kwargs)
+ except concurrent.futures.TimeoutError as e:
+ try:
+ # The job would run on, and bill the customer, with nothing to read its result.
+ job.cancel(timeout=BIGQUERY_HTTP_TIMEOUT_SECONDS[1])
+ except Exception as cancel_error:
+ structlog.get_logger().debug("Could not cancel a BigQuery job at its limit", error=str(cancel_error))
+ raise BigQueryJobTimeoutError(timeout_seconds) from e
+
+
+def _pages_with_idle_timeout(
+ pages: Iterator[_T], *, timeout_seconds: float, end_read: Callable[[], None]
+) -> Iterator[_T]:
+ """Yield `pages`, and raise `BigQueryReadTimeoutError` when one does not come in time.
+
+ A gRPC deadline covers the stream as a whole, so it cannot tell a silent stream from a long
+ one. At the limit a timer thread calls `end_read`, which must make the blocked read raise.
+ """
+ while True:
+ expired = threading.Event()
+
+ def _expire(expired: threading.Event = expired) -> None:
+ expired.set()
+ end_read()
+
+ timer = threading.Timer(timeout_seconds, _expire)
+ timer.daemon = True
+ timer.start()
+ try:
+ page = next(pages)
+ except StopIteration:
+ return
+ except Exception as e:
+ if expired.is_set():
+ raise BigQueryReadTimeoutError(timeout_seconds) from e
+ raise
+ finally:
+ timer.cancel()
+ yield page
+
+
# `job_retry` recovers a failed query *job* (a retryable reason surfaced from `jobs.getQueryResults`);
# `retry` recovers the job-*creation* API call (`jobs.insert`). BigQuery's transient queued-jobs quota
# is rejected at insert, which `job_retry` never wraps, so the create path needs its own retry.
@@ -645,7 +763,7 @@ def bigquery_client(
# AuthorizedSession is a `requests.Session` subclass that injects the OAuth2
# bearer token. Mount our TrackedHTTPAdapter on it so every BigQuery REST
# call is logged and metered alongside the other warehouse sources.
- authed_session = AuthorizedSession(credentials, auth_request=GoogleAuthRequest(auth_request_session))
+ authed_session = _DeadlineAuthorizedSession(credentials, auth_request=GoogleAuthRequest(auth_request_session))
tracked_adapter = TrackedHTTPAdapter(max_retries=DEFAULT_RETRY)
authed_session.mount("https://", tracked_adapter)
authed_session.mount("http://", tracked_adapter)
@@ -702,6 +820,7 @@ def bigquery_storage_read_client(credentials: google_auth_credentials.Credential
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
+ *_BIGQUERY_STORAGE_KEEPALIVE_OPTIONS,
],
)
tracked_channel = make_tracked_channel(channel, host=BIGQUERY_STORAGE_HOST)
@@ -1101,7 +1220,14 @@ def _get_rows_to_sync(
query = f"SELECT COUNT(*) FROM ({inner_query}) as t"
job_config = QueryJobConfig(query_parameters=query_parameters)
- rows = _query_result_with_job_retry(client, query, job_config=job_config, project=table.project, page_size=1)
+ rows = _query_result_with_job_retry(
+ client,
+ query,
+ job_config=job_config,
+ project=table.project,
+ page_size=1,
+ timeout_seconds=BIGQUERY_ROW_COUNT_JOB_TIMEOUT_SECONDS,
+ )
row = next(rows, None)
if row and len(row) > 0 and row[0] is not None:
@@ -1114,7 +1240,7 @@ def _get_rows_to_sync(
return 0
except Exception as e:
logger.debug(f"_get_rows_to_sync: Error: {e}. Using 0 as rows to sync", exc_info=e)
- if not _is_missing_table_or_dataset(e):
+ if not _is_missing_table_or_dataset(e) and not isinstance(e, BigQueryJobTimeoutError):
capture_exception(e)
return 0
@@ -1352,7 +1478,7 @@ def _run_destination_query_with_job_retry(
def _run() -> None:
job = client.query(query, job_config=job_config, project=project, retry=BIGQUERY_QUERY_CREATE_RETRY)
- job.result(job_retry=BIGQUERY_QUERY_JOB_RETRY)
+ _wait_for_job(job, timeout_seconds=BIGQUERY_COPY_JOB_TIMEOUT_SECONDS, job_retry=BIGQUERY_QUERY_JOB_RETRY)
_with_job_not_found_retry(_run)
@@ -1364,6 +1490,7 @@ def _query_result_with_job_retry(
job_config: QueryJobConfig,
project: str,
page_size: int | None = None,
+ timeout_seconds: float | None = None,
) -> RowIterator:
"""Run a read-only query and return its row iterator, retrying the transient job-metadata race.
@@ -1375,7 +1502,11 @@ def _query_result_with_job_retry(
def _run() -> RowIterator:
job = client.query(query, job_config=job_config, project=project, retry=BIGQUERY_QUERY_CREATE_RETRY)
- return job.result(page_size=page_size, job_retry=BIGQUERY_QUERY_JOB_RETRY)
+ if timeout_seconds is None:
+ return job.result(page_size=page_size, job_retry=BIGQUERY_QUERY_JOB_RETRY)
+ return _wait_for_job(
+ job, timeout_seconds=timeout_seconds, page_size=page_size, job_retry=BIGQUERY_QUERY_JOB_RETRY
+ )
return _with_job_not_found_retry(_run)
@@ -1856,7 +1987,12 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu
record_batches = []
table_size_bytes = 0
- for page in rows_iterator.pages:
+ pages = _pages_with_idle_timeout(
+ iter(rows_iterator.pages),
+ timeout_seconds=BIGQUERY_READ_ROWS_IDLE_TIMEOUT_SECONDS,
+ end_read=bq_storage.transport.close,
+ )
+ for page in pages:
record_batch = page.to_arrow()
# TODO: Perhaps we should support slicing record batches like we do in batch exports.
table_size_bytes += record_batch.get_total_buffer_size()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py
index 36422a3487f3..f2421d6fb77f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/source.py
@@ -23,10 +23,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
BIGQUERY_INVALID_IDENTIFIER_ERROR,
BIGQUERY_INVALID_KEY_FILE_ERROR,
BIGQUERY_INVALID_TOKEN_URI_ERROR,
+ BIGQUERY_JOB_TIMEOUT_ERROR,
BIGQUERY_MISSING_KEY_FILE_FIELDS_ERROR,
BIGQUERY_NO_CREDENTIALS_ERROR,
BIGQUERY_ON_DEMAND_RATIO_EXCEEDED_ERROR,
BIGQUERY_OWNERSHIP_UNVERIFIED_ERROR_PREFIX,
+ BIGQUERY_READ_TIMEOUT_ERROR,
BIGQUERY_RESOURCES_EXCEEDED_ERROR,
BIGQUERY_SERVICE_ACCOUNT_NOT_FOUND_ERROR,
BIGQUERY_TOKEN_RESPONSE_ERROR,
@@ -81,6 +83,11 @@ class BigQuerySource(SQLSource[BigQuerySourceConfig]):
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BIGQUERY
+ def get_retryable_errors(self) -> set[str]:
+ # The client-side limits on a query job and on the wait for one page of rows. BigQuery was
+ # reachable and then gave no result in time, so a later attempt can succeed.
+ return {BIGQUERY_JOB_TIMEOUT_ERROR, BIGQUERY_READ_TIMEOUT_ERROR}
+
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
# google-api-core raises `PermissionDenied` from the Storage Read API's
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
index abdf1bfc9fc8..1c565b4e93da 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -1,3 +1,5 @@
+import threading
+import concurrent.futures
from types import SimpleNamespace
from typing import cast
@@ -11,6 +13,7 @@ from google.api_core.exceptions import (
DeadlineExceeded,
Forbidden,
InternalServerError,
+ InvalidArgument,
NotFound,
PermissionDenied,
ServiceUnavailable,
@@ -23,11 +26,14 @@ from posthog.models.integration import Integration
from posthog.models.team.team import Team
from products.batch_exports.backend.facade.destinations.bigquery import ServiceAccountOwnershipError
+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery import bigquery as bq_module
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import (
+ BIGQUERY_COPY_JOB_TIMEOUT_SECONDS,
BIGQUERY_CREATE_READ_SESSION_RETRY,
BIGQUERY_CREDENTIALS_REJECTED_ERROR,
BIGQUERY_DATASET_NOT_FOUND_ERROR,
+ BIGQUERY_HTTP_TIMEOUT_SECONDS,
BIGQUERY_IMPERSONATION_PERMISSION_ERROR,
BIGQUERY_INTEGRATION_NOT_FOUND_ERROR,
BIGQUERY_INVALID_IDENTIFIER_ERROR,
@@ -38,6 +44,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
BIGQUERY_QUERY_CREATE_RETRY,
BIGQUERY_QUERY_JOB_RETRY,
BIGQUERY_READ_ROWS_RETRY,
+ BIGQUERY_ROW_COUNT_JOB_TIMEOUT_SECONDS,
BIGQUERY_TOKEN_REFRESH_RETRY,
BIGQUERY_TOKEN_RESPONSE_ERROR,
BIGQUERY_VALIDATION_GENERIC_ERROR,
@@ -48,12 +55,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
BigQueryImplementation,
BigQueryInvalidIdentifierError,
BigQueryInvalidTokenUriError,
+ BigQueryJobTimeoutError,
+ BigQueryReadTimeoutError,
BigQueryTokenRefreshError,
_bq_select_clause,
_get_primary_keys_for_table,
_get_query,
_get_rows_to_sync,
_has_duplicate_primary_keys,
+ _pages_with_idle_timeout,
_resolve_region,
_run_destination_query_with_job_retry,
delete_all_temp_destination_tables,
@@ -61,6 +71,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.b
validate_bigquery_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.source import BigQuerySource
+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.identifiers import (
InvalidIdentifierError,
)
@@ -1552,3 +1563,122 @@ def test_bigquery_validate_config_reads_a_bare_selection_from_the_flat_payload(j
assert not any("Required field" in error for error in errors)
if not expected_valid:
assert any("Google Cloud service account" in error for error in errors)
+
+
+ "caller_timeout, sent_timeout",
+ [(None, BIGQUERY_HTTP_TIMEOUT_SECONDS), (5.0, 5.0)],
+ ids=["client_default_of_none", "explicit_timeout_is_kept"],
+)
+def test_bigquery_rest_requests_always_have_a_timeout(caller_timeout, sent_timeout):
+ # The BigQuery client passes `timeout=None` for each call without one, and `requests` then
+ # waits on a silent server without limit.
+ with (
+ bq_module.bigquery_client(
+ project_id="project-id", location=None, credentials=mock.Mock(spec=GoogleAuthCredentials)
+ ) as client,
+ mock.patch.object(bq_module.AuthorizedSession, "request") as request,
+ ):
+ client._http.request("GET", "https://bigquery.googleapis.com/x", timeout=caller_timeout)
+
+ assert request.call_args.kwargs["timeout"] == sent_timeout
+
+
[email protected]("cancel_error", [None, RuntimeError("cancel refused")], ids=["cancelled", "cancel_fails"])
+def test_copy_job_past_its_limit_is_cancelled_and_raises_a_retryable_error(cancel_error):
+ client = mock.MagicMock()
+ job = client.query.return_value
+ job.result.side_effect = concurrent.futures.TimeoutError()
+ job.cancel.side_effect = cancel_error
+
+ with pytest.raises(BigQueryJobTimeoutError) as error:
+ _run_destination_query_with_job_retry(
+ client, "SELECT 1", destination_table=mock.MagicMock(), query_parameters=[], project="prj"
+ )
+
+ assert job.result.call_args.kwargs["timeout"] == BIGQUERY_COPY_JOB_TIMEOUT_SECONDS
+ job.cancel.assert_called_once()
+ _assert_retryable(str(error.value))
+
+
+def test_bigquery_get_rows_to_sync_gives_zero_when_the_count_is_past_its_limit():
+ table = mock.MagicMock(project="proj", dataset_id="ds", table_id="t")
+ table.schema = [SimpleNamespace(name="age", field_type="INTEGER")]
+ client = mock.MagicMock()
+ job = client.query.return_value
+ job.result.side_effect = concurrent.futures.TimeoutError()
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery.capture_exception"
+ ) as mock_capture:
+ result = _get_rows_to_sync(
+ table=table,
+ client=client,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ logger=mock.MagicMock(),
+ row_filters=[
+ ValidatedRowFilter(column="age", operator="IN", value=[21, 30], category=ColumnTypeCategory.INTEGER)
+ ],
+ )
+
+ assert result == 0
+ assert job.result.call_args.kwargs["timeout"] == BIGQUERY_ROW_COUNT_JOB_TIMEOUT_SECONDS
+ # A slow count is expected on a large filtered table, so it is not an error to track.
+ mock_capture.assert_not_called()
+
+
+def _assert_retryable(message: str) -> None:
+ source = BigQuerySource()
+ assert error_message_matches(message, source.get_retryable_errors())
+ assert not error_message_matches(message, {**Any_Source_Errors, **source.get_non_retryable_errors()})
+
+
+def test_row_pages_that_keep_coming_never_end_the_read():
+ end_read = mock.Mock()
+
+ pages = list(_pages_with_idle_timeout(iter([1, 2, 3]), timeout_seconds=30, end_read=end_read))
+
+ assert pages == [1, 2, 3]
+ end_read.assert_not_called()
+
+
+def test_each_row_page_gets_its_own_wait_limit(monkeypatch):
+ # A limit on the stream as a whole would end a long read that is in good health.
+ timers: list[mock.Mock] = []
+
+ def fake_timer(interval, function):
+ timers.append(mock.Mock(interval=interval))
+ return timers[-1]
+
+ monkeypatch.setattr(bq_module.threading, "Timer", fake_timer)
+
+ list(_pages_with_idle_timeout(iter([1, 2]), timeout_seconds=600, end_read=mock.Mock()))
+
+ # One wait for each page, and one for the end of the stream.
+ assert [timer.interval for timer in timers] == [600, 600, 600]
+ assert all(timer.start.called and timer.cancel.called for timer in timers)
+
+
+def test_row_page_that_does_not_come_ends_the_read_with_a_retryable_error():
+ ended = threading.Event()
+
+ def silent_stream():
+ yield "first page"
+ assert ended.wait(5)
+ raise ValueError("Cannot invoke RPC on closed channel!")
+
+ taken = []
+ with pytest.raises(BigQueryReadTimeoutError) as error:
+ for page in _pages_with_idle_timeout(silent_stream(), timeout_seconds=0.05, end_read=ended.set):
+ taken.append(page)
+
+ assert taken == ["first page"]
+ _assert_retryable(str(error.value))
+
+
+def test_row_page_error_before_the_limit_keeps_its_own_class():
+ broken_stream = iter(mock.Mock(side_effect=InvalidArgument("the read session is not valid")), None)
+
+ with pytest.raises(InvalidArgument):
+ list(_pages_with_idle_timeout(broken_stream, timeout_seconds=30, end_read=mock.Mock()))
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 605a0015552a..0aa33ebe2c0d 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
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
import math
import uuid
import base64
@@ -61,6 +62,21 @@ SCHEMA_INFERENCE_TIMEOUT_MS = 45_000 # 45 seconds
ROW_COUNT_TIMEOUT_MS = 60_000
COLLECTION_STATS_TIMEOUT_MS = 30_000
+# Client-side limits of each connection. pymongo has no socket timeout by default, so a server that
+# stops answering holds a `find` or a `getMore` for as long as the socket stays open.
+SERVER_SELECTION_TIMEOUT_MS = 10_000
+CONNECT_TIMEOUT_MS = 10_000
+# The wait for one answer from the server: the first batch of a cursor, or one `getMore`. A read
+# that keeps returning batches starts a new wait with each one, so this is not a limit on the read.
+# The data cursor gets no `maxTimeMS`, because the server counts that limit over the cursor as a
+# whole and it would end a long read that is in good health.
+SOCKET_TIMEOUT_MS = 10 * 60 * 1000
+# A limit that the connection string sets itself is kept.
+_CONNECTION_TIMEOUT_DEFAULTS: dict[str, int] = {
+ "connectTimeoutMS": CONNECT_TIMEOUT_MS,
+ "socketTimeoutMS": SOCKET_TIMEOUT_MS,
+}
+
# 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
@@ -316,12 +332,21 @@ def _make_safe_server_selector(team_id: int) -> Callable[[list[ServerDescription
return selector
+def connection_timeouts(connection_string: str) -> dict[str, int]:
+ """The connect and socket timeouts to pass to `MongoClient`, less those the connection string sets."""
+ option_keys = {
+ option.partition("=")[0].lower() for option in re.split(r"[&;]", connection_string.partition("?")[2])
+ }
+ return {name: value for name, value in _CONNECTION_TIMEOUT_DEFAULTS.items() if name.lower() not in option_keys}
+
+
@contextlib.contextmanager
def mongo_client(connection_string: str, team_id: int) -> Iterator[MongoClient]:
# rpartition strips credentials; multiple hosts stay comma-joined as-is.
log_connection_open(db_host=urlparse(connection_string).netloc.rpartition("@")[2], team_id=team_id)
kwargs: dict[str, Any] = {
- "serverSelectionTimeoutMS": 10000,
+ "serverSelectionTimeoutMS": SERVER_SELECTION_TIMEOUT_MS,
+ **connection_timeouts(connection_string),
"tls": True,
"tlsCAFile": certifi.where(),
"server_selector": _make_safe_server_selector(team_id),
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 9c697141af6c..b2a15167d61b 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
@@ -22,6 +22,7 @@ from pymongo.errors import CursorNotFound, ExecutionTimeout, OperationFailure, S
from pymongo.hello import Hello
from pymongo.server_description import ServerDescription
+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import DEFAULT_CHUNK_SIZE
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.mixins import (
@@ -30,10 +31,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo import (
+ CONNECT_TIMEOUT_MS,
MONGO_DOCUMENT_MISSING_ID_ERROR,
MONGO_KEYS_UNAVAILABLE_ERROR,
MONGO_MAX_CHUNK_ROWS,
MONGO_MIN_CHUNK_ROWS,
+ SERVER_SELECTION_TIMEOUT_MS,
+ SOCKET_TIMEOUT_MS,
MongoResumeConfig,
_adaptive_chunk_size,
_build_query,
@@ -45,11 +49,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mo
_make_safe_server_selector,
_process_doc_with_field_logging,
_process_nested_value,
+ connection_timeouts,
decode_resume_id,
encode_resume_id,
get_index_keys,
get_index_keys_by_collection,
get_server_metadata,
+ mongo_client,
mongo_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.source import MongoDBSource
@@ -1223,3 +1229,68 @@ class TestGetServerMetadata(SimpleTestCase):
assert "wire_version" not in metadata
else:
assert metadata["wire_version"] == expected_wire_version
+
+
+_MONGO_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.mongodb.mongo"
+
+
+class TestConnectionTimeouts(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "no_options",
+ "mongodb+srv://user:[email protected]/db",
+ {"connectTimeoutMS": CONNECT_TIMEOUT_MS, "socketTimeoutMS": SOCKET_TIMEOUT_MS},
+ ),
+ (
+ "other_options_only",
+ "mongodb://user:[email protected]:27017/db?retryWrites=true&w=majority&tls=true",
+ {"connectTimeoutMS": CONNECT_TIMEOUT_MS, "socketTimeoutMS": SOCKET_TIMEOUT_MS},
+ ),
+ (
+ "socket_timeout_in_the_connection_string",
+ "mongodb://user:[email protected]/db?socketTimeoutMS=900000&tls=true",
+ {"connectTimeoutMS": CONNECT_TIMEOUT_MS},
+ ),
+ (
+ "option_names_are_not_case_sensitive",
+ "mongodb://user:[email protected]/db?connecttimeoutms=5000&SOCKETTIMEOUTMS=5000&tls=true",
+ {},
+ ),
+ (
+ "an_option_name_in_another_options_value_is_not_an_option",
+ "mongodb://user:[email protected]/db?appName=import-socketTimeoutMS=1&tls=true",
+ {"connectTimeoutMS": CONNECT_TIMEOUT_MS, "socketTimeoutMS": SOCKET_TIMEOUT_MS},
+ ),
+ (
+ "an_option_name_in_the_credentials_is_not_an_option",
+ "mongodb://sockettimeoutms=1:[email protected]/db?tls=true",
+ {"connectTimeoutMS": CONNECT_TIMEOUT_MS, "socketTimeoutMS": SOCKET_TIMEOUT_MS},
+ ),
+ ]
+ )
+ def test_default_timeouts_give_way_to_the_connection_string(self, _name, connection_string, expected):
+ # A keyword argument to `MongoClient` wins over the connection string, so a default that
+ # was always sent would discard the limit a customer chose.
+ assert connection_timeouts(connection_string) == expected
+
+ def test_client_limits_server_selection_connect_and_each_socket_wait(self):
+ with patch(f"{_MONGO_MODULE}.MongoClient") as client_class:
+ with mongo_client("mongodb://user:[email protected]/db?tls=true", team_id=1):
+ pass
+
+ kwargs = client_class.call_args.kwargs
+ assert kwargs["serverSelectionTimeoutMS"] == SERVER_SELECTION_TIMEOUT_MS
+ assert kwargs["connectTimeoutMS"] == CONNECT_TIMEOUT_MS
+ assert kwargs["socketTimeoutMS"] == SOCKET_TIMEOUT_MS
+
+ def test_socket_timeout_error_is_retryable(self):
+ # pymongo's NetworkTimeout wording when a socket read reaches `socketTimeoutMS`.
+ message = (
+ "db.example.com:27017: timed out (configured timeouts: socketTimeoutMS: 600000.0ms, "
+ "connectTimeoutMS: 10000.0ms)"
+ )
+ source = MongoDBSource()
+
+ assert error_message_matches(message, source.get_retryable_errors())
+ assert not error_message_matches(message, {**Any_Source_Errors, **source.get_non_retryable_errors()})
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 38c4a2bd31c6..40c28eddea82 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
@@ -84,6 +84,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.redshift import (
RedshiftSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.client_deadline import (
+ ClientDeadlineExceededError,
+ client_side_deadline,
+)
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
from products.warehouse_sources.backend.types import IncrementalFieldType, PartitionSettings
@@ -119,6 +123,46 @@ __all__ = [
# `start_to_close_timeout` of its Temporal activity.
METADATA_STATEMENT_TIMEOUT_MS = 1000 * 60 * 5
+# Client-side limits on the wait for one batch of rows. The connection that reads the rows has no
+# session statement timeout, because that limit covers the statement as a whole and would end a
+# long read that is in good health. These limits cover one silent wait, and each batch starts a new
+# one. The first batch includes the query, which sorts the full result of an incremental read
+# before it returns a row.
+STREAM_FIRST_BATCH_DEADLINE_SECONDS = 30 * 60
+STREAM_NEXT_BATCH_DEADLINE_SECONDS = 10 * 60
+
+# Stable prefix, matched by `RedshiftSource.get_retryable_errors`.
+REDSHIFT_READ_TIMEOUT_ERROR = "Redshift sent no rows"
+
+_END_OF_BATCHES: Any = object()
+
+
+class RedshiftReadTimeoutError(Exception):
+ """Redshift sent no batch of rows before the deadline. A later attempt can succeed."""
+
+ def __init__(self, timeout_seconds: float) -> None:
+ super().__init__(f"{REDSHIFT_READ_TIMEOUT_ERROR} for {timeout_seconds:g} seconds, so PostHog ended the read")
+
+
+def _batches_with_idle_deadline(connection: psycopg.Connection, batches: Iterator[Any]) -> Iterator[Any]:
+ """Yield `batches`, and end the statement when one batch does not come in time.
+
+ At the deadline the statement gets a cancel request, and the socket is shut down if that has
+ no effect (see `client_side_deadline`).
+ """
+ timeout_seconds: float = STREAM_FIRST_BATCH_DEADLINE_SECONDS
+ while True:
+ try:
+ with client_side_deadline(connection, timeout_seconds):
+ batch = next(batches, _END_OF_BATCHES)
+ except ClientDeadlineExceededError as e:
+ raise RedshiftReadTimeoutError(timeout_seconds) from e
+ if batch is _END_OF_BATCHES:
+ return
+ yield batch
+ timeout_seconds = STREAM_NEXT_BATCH_DEADLINE_SECONDS
+
+
_REDSHIFT_CONNECT_OPTS: dict[str, Any] = {
"sslmode": "require",
"connect_timeout": 15,
@@ -819,17 +863,23 @@ def _stream_arrow_batches(
try:
with connection.cursor() as stream_cursor:
- for batch in _stream_rows_as_arrow_batches(
- stream_cursor,
- query,
- chunk_size,
- arrow_schema,
- primary_keys=primary_keys,
- binary_reporter=binary_reporter,
+ for batch in _batches_with_idle_deadline(
+ connection,
+ _stream_rows_as_arrow_batches(
+ stream_cursor,
+ query,
+ chunk_size,
+ arrow_schema,
+ primary_keys=primary_keys,
+ binary_reporter=binary_reporter,
+ ),
):
yielded = True
yield batch
return
+ except RedshiftReadTimeoutError:
+ # The cursor fallback runs the same query on the same silent cluster.
+ raise
except Exception as e:
if yielded:
raise
@@ -845,18 +895,26 @@ def _stream_arrow_batches(
# `close()` is a no-op while the transaction is aborted (psycopg checks the status
# first), so this never masks the original failure with a CLOSE error.
with connection.cursor(name=cursor_name) as server_cursor:
- server_cursor.execute(query)
- for batch in _fetch_arrow_batches(
- server_cursor,
- chunk_size,
- arrow_schema,
- fetch_size,
- primary_keys=primary_keys,
- binary_reporter=binary_reporter,
+ with client_side_deadline(connection, STREAM_FIRST_BATCH_DEADLINE_SECONDS):
+ server_cursor.execute(query)
+ for batch in _batches_with_idle_deadline(
+ connection,
+ _fetch_arrow_batches(
+ server_cursor,
+ chunk_size,
+ arrow_schema,
+ fetch_size,
+ primary_keys=primary_keys,
+ binary_reporter=binary_reporter,
+ ),
):
yielded = True
yield batch
return
+ except ClientDeadlineExceededError as e:
+ raise RedshiftReadTimeoutError(STREAM_FIRST_BATCH_DEADLINE_SECONDS) from e
+ except RedshiftReadTimeoutError:
+ raise
except Exception as e:
if yielded:
raise
@@ -2077,7 +2135,9 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
logger,
)
streaming_connection.adapters.register_loader("json", JsonAsStringLoader)
- projection = _refreshed_projection(streaming_connection)
+ # This connection has no statement timeout, so the catalog re-read gets a client one.
+ with client_side_deadline(streaming_connection, METADATA_STATEMENT_TIMEOUT_MS / 1000):
+ projection = _refreshed_projection(streaming_connection)
table = projection.table
arrow_schema = table.to_arrow_schema()
query = _build_query(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py
index 1932af4ec3c8..84ac9a1fa312 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/source.py
@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
RedshiftSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift import (
+ REDSHIFT_READ_TIMEOUT_ERROR,
RedshiftImplementation,
get_connection_metadata as get_connection_metadata_redshift,
)
@@ -173,10 +174,21 @@ class RedshiftSource(SQLSource[RedshiftSourceConfig], SSHTunnelMixin, ValidateDa
def get_retryable_errors(self) -> set[str]:
# The bounded lookup in front of every connect raises these when the resolver stalls or
# answers "try again". Neither is a verdict on the host, so a fresh attempt recovers.
- return {HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERROR}
+ #
+ # `REDSHIFT_READ_TIMEOUT_ERROR` is the client-side limit on the wait for one batch of rows.
+ # The cluster was reachable and then sent nothing, so a later attempt can succeed.
+ return {HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERROR, REDSHIFT_READ_TIMEOUT_ERROR}
def get_retry_exhausted_errors(self) -> dict[str, str]:
- return dict.fromkeys(self.get_retryable_errors(), HOST_RESOLUTION_EXHAUSTED_MESSAGE)
+ return {
+ HOST_RESOLUTION_TIMEOUT_ERROR: HOST_RESOLUTION_EXHAUSTED_MESSAGE,
+ TEMPORARY_HOST_RESOLUTION_ERROR: HOST_RESOLUTION_EXHAUSTED_MESSAGE,
+ REDSHIFT_READ_TIMEOUT_ERROR: (
+ "Your Redshift cluster stopped sending rows in the middle of the sync, and it did so again "
+ "on every retry. Check that the cluster is not paused or resizing and that it has capacity "
+ "for the read. This sync is still enabled and will run again on its next schedule."
+ ),
+ }
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
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 e21eb8317257..1ca232d33992 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
@@ -1,4 +1,6 @@
+import threading
from collections.abc import Callable
+from contextlib import contextmanager
from datetime import UTC, date, datetime
from typing import Any
@@ -13,9 +15,11 @@ from sshtunnel import BaseSSHTunnelForwarderError
from posthog.psycopg_helpers import HOST_RESOLUTION_TIMEOUT_ERROR, TEMPORARY_HOST_RESOLUTION_ERROR
+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
TemporaryFileSizeExceedsLimitException,
)
+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.mixins import (
HostNotAllowedError,
TemporaryHostResolutionError,
@@ -31,8 +35,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift import (
REDSHIFT_SINGLE_NODE_FETCH_LIMIT,
+ STREAM_FIRST_BATCH_DEADLINE_SECONDS,
+ STREAM_NEXT_BATCH_DEADLINE_SECONDS,
RedshiftColumn,
RedshiftImplementation,
+ RedshiftReadTimeoutError,
SafeDateLoader,
SafeTimestampLoader,
SafeTimestamptzLoader,
@@ -523,6 +530,7 @@ class TestFetchAverageRowSize:
# ---------------------------------------------------------------------------
+_REDSHIFT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift"
_STREAM_SCHEMA = pa.schema([pa.field("id", pa.int64())])
_STREAM_QUERY = sql.SQL("SELECT id FROM public.t").format()
@@ -643,6 +651,57 @@ class TestStreamArrowBatches:
# Re-running the query here would re-emit rows the pipeline already merged.
server_cursor.execute.assert_not_called()
+ def test_each_batch_gets_its_own_wait_limit(self, logger, mocker):
+ # A limit on the read as a whole would end a long read that is in good health.
+ deadlines: list[float] = []
+
+ @contextmanager
+ def record_deadline(_connection, timeout_seconds):
+ deadlines.append(timeout_seconds)
+ yield
+
+ mocker.patch(f"{_REDSHIFT_MODULE}.client_side_deadline", record_deadline)
+ connection = _stream_connection(_stream_cursor([]), _rows_cursor([(1,), (2,), (3,)]))
+
+ list(_stream_arrow_batches(connection, _STREAM_QUERY, 2, _STREAM_SCHEMA, "cur", logger))
+
+ # Two batches, then the wait that finds the end of the result.
+ assert deadlines == [
+ STREAM_FIRST_BATCH_DEADLINE_SECONDS,
+ STREAM_NEXT_BATCH_DEADLINE_SECONDS,
+ STREAM_NEXT_BATCH_DEADLINE_SECONDS,
+ ]
+
+ @pytest.mark.parametrize("read_path", ["stream", "server_cursor"])
+ def test_a_silent_cluster_ends_the_read_with_a_retryable_error(self, logger, mocker, read_path):
+ mocker.patch(f"{_REDSHIFT_MODULE}.STREAM_FIRST_BATCH_DEADLINE_SECONDS", 0.05)
+ cancelled = threading.Event()
+
+ def silent_until_cancelled(*args, **kwargs):
+ assert cancelled.wait(5)
+ raise psycopg.errors.QueryCanceled("canceling statement due to user request")
+
+ if read_path == "stream":
+ stream_cursor = _rows_cursor([])
+ stream_cursor.stream.side_effect = silent_until_cancelled
+ server_cursor = _stream_cursor([[(9,)]])
+ else:
+ stream_cursor = _rows_cursor(psycopg.errors.FeatureNotSupported("single row mode not supported"))
+ server_cursor = _stream_cursor([])
+ server_cursor.fetchmany.side_effect = silent_until_cancelled
+ connection = _stream_connection(server_cursor, stream_cursor)
+ connection.cancel_safe.side_effect = lambda timeout: cancelled.set()
+
+ with pytest.raises(RedshiftReadTimeoutError) as error:
+ list(_stream_arrow_batches(connection, _STREAM_QUERY, 2, _STREAM_SCHEMA, "cur", logger))
+
+ if read_path == "stream":
+ # The cursor fallback would run the same query on the same silent cluster.
+ server_cursor.execute.assert_not_called()
+ source = RedshiftSource()
+ assert error_message_matches(str(error.value), source.get_retryable_errors())
+ assert not error_message_matches(str(error.value), {**Any_Source_Errors, **source.get_non_retryable_errors()})
+
class TestHasDuplicatePrimaryKeys:
def test_returns_false_when_no_pks(self, impl, cursor, logger):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
index 99acdaca402d..08d78d3061f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
@@ -133,10 +133,24 @@ _SNOWFLAKE_NETWORK_TIMEOUT_SECONDS = 300
# `ProgrammingError` 000604 (57014, "SQL execution was cancelled by the client due to a timeout").
# That's harmless for the short metadata queries, but it must not cancel a legitimately long
# full-table data scan — so those pass this explicit, much larger per-query `timeout`, overriding the
-# timebomb while leaving the retry budget above intact. It mirrors the import activity's 6h
-# `start_to_close_timeout`, which is the real ceiling: the connector defers to Temporal rather than
-# pre-empting a sync that is still making progress.
-_SNOWFLAKE_QUERY_TIMEOUT_SECONDS = 6 * 60 * 60
+# timebomb while leaving the retry budget above intact.
+#
+# This is the limit on the time to the first row: `execute` returns only when Snowflake has the
+# result, and the worker cannot hand the import to another worker before that. While the query runs
+# the connector polls for the result, and `network_timeout` limits each of those requests, so this
+# is not the limit on a silent connection.
+_SNOWFLAKE_QUERY_TIMEOUT_SECONDS = 2 * 60 * 60
+
+# The count scans the same rows as the read, on each attempt, before the first row is read. Its
+# result feeds the progress display and the billing limit check only, so a count that is not done
+# by this time gives 0 (unknown).
+_SNOWFLAKE_ROW_COUNT_TIMEOUT_SECONDS = 120
+
+# The login request. The connector default is 120 seconds.
+_SNOWFLAKE_LOGIN_TIMEOUT_SECONDS = 60
+
+# The connector's wording when it cancels a query at its `timeout`.
+_SNOWFLAKE_CLIENT_TIMEOUT_MESSAGE = "SQL execution was cancelled by the client due to a timeout"
def _split_display_name(display_name: str, default_schema: Optional[str]) -> tuple[Optional[str], str]:
@@ -345,6 +359,7 @@ class SnowflakeImplementation(
# `schema=""` would try `USE SCHEMA ""`, an invalid identifier, and fail at connect time.
schema=normalize_namespace(config.schema),
role=config.role,
+ login_timeout=_SNOWFLAKE_LOGIN_TIMEOUT_SECONDS,
network_timeout=_SNOWFLAKE_NETWORK_TIMEOUT_SECONDS,
**auth_connect_args,
) as connection:
@@ -630,7 +645,7 @@ class SnowflakeImplementation(
try:
query = f"SELECT COUNT(*) FROM ({inner_query}) as t"
- cursor.execute(query, inner_query_args, timeout=_SNOWFLAKE_QUERY_TIMEOUT_SECONDS)
+ cursor.execute(query, inner_query_args, timeout=_SNOWFLAKE_ROW_COUNT_TIMEOUT_SECONDS)
row = cursor.fetchone()
if row is None:
@@ -644,7 +659,9 @@ class SnowflakeImplementation(
return rows_to_sync_int
except Exception as e:
logger.debug(f"get_rows_to_sync: Error: {e}. Using 0 as rows to sync", exc_info=e)
- capture_exception(e)
+ # A count past its limit is expected on a large table, so it is not an error to track.
+ if _SNOWFLAKE_CLIENT_TIMEOUT_MESSAGE not in str(e):
+ capture_exception(e)
return 0
# ------------------------------------------------------------------
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
index b1b2bd789d4c..cb1d86b8da65 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
@@ -9,10 +9,14 @@ import pyarrow as pa
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
-from snowflake.connector.errors import DatabaseError, HttpError, OperationalError
+from snowflake.connector.errors import DatabaseError, HttpError, OperationalError, ProgrammingError
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ResumableSource,
+ error_message_matches,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ColumnTypeCategory,
ValidatedRowFilter,
@@ -23,8 +27,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import source_requires_ssl
from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake import (
+ _SNOWFLAKE_LOGIN_TIMEOUT_SECONDS,
_SNOWFLAKE_NETWORK_TIMEOUT_SECONDS,
_SNOWFLAKE_QUERY_TIMEOUT_SECONDS,
+ _SNOWFLAKE_ROW_COUNT_TIMEOUT_SECONDS,
SnowflakeImplementation,
SnowflakeResumeState,
_batch_checkpoint,
@@ -421,6 +427,7 @@ class TestConnect:
mock_connect.return_value.__enter__.return_value = MagicMock()
with impl.connect(_make_config()):
pass
+ assert mock_connect.call_args.kwargs["login_timeout"] == _SNOWFLAKE_LOGIN_TIMEOUT_SECONDS
network_timeout = mock_connect.call_args.kwargs["network_timeout"]
# A finite, positive bound is the invariant. `0` reads as infinite to the connector, so
# guard that explicitly — equality alone can't catch the constant regressing to `0`.
@@ -666,14 +673,35 @@ class TestGetRowsToSync:
def test_returns_count(self, impl, cursor, logger):
cursor.fetchone.return_value = (321,)
assert impl.get_rows_to_sync(cursor, "SELECT 1", (), logger) == 321
- # The COUNT(*) probe scans the same table, so it carries the same long per-query timeout —
- # otherwise a large table trips the connector timebomb and the probe spuriously logs a 604.
- assert cursor.execute.call_args.kwargs["timeout"] == _SNOWFLAKE_QUERY_TIMEOUT_SECONDS
+ # The count runs before the first row on each attempt, so it must not get the long limit
+ # of the read.
+ assert cursor.execute.call_args.kwargs["timeout"] == _SNOWFLAKE_ROW_COUNT_TIMEOUT_SECONDS
- def test_returns_zero_on_exception(self, impl, cursor, logger):
+ @pytest.mark.parametrize(
+ "error, expect_capture",
+ [
+ (RuntimeError("boom"), True),
+ # The connector's error when the count reaches its `timeout`.
+ (
+ ProgrammingError(
+ msg="SQL execution was cancelled by the client due to a timeout. "
+ "Error message received from the server: SQL execution canceled",
+ errno=604,
+ sqlstate="57014",
+ ),
+ False,
+ ),
+ ],
+ ids=["unexpected_error", "count_past_its_limit"],
+ )
+ def test_returns_zero_on_exception(self, impl, cursor, logger, error, expect_capture):
# Sync must never bail because the COUNT(*) probe failed
- cursor.execute.side_effect = RuntimeError("boom")
- assert impl.get_rows_to_sync(cursor, "SELECT 1", (), logger) == 0
+ cursor.execute.side_effect = error
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake.capture_exception"
+ ) as mock_capture:
+ assert impl.get_rows_to_sync(cursor, "SELECT 1", (), logger) == 0
+ assert mock_capture.called is expect_capture
# ---------------------------------------------------------------------------
@@ -1210,6 +1238,8 @@ class TestSnowflakeSourceRetryableErrors:
retryable = source.get_retryable_errors()
is_retryable = any(pattern in error_msg for pattern in retryable)
assert is_retryable, f"Client-side query-timeout cancellation should be classified retryable: {error_msg}"
+ # The read query reaches the same error at its own limit, and that must not stop the sync.
+ assert not error_message_matches(error_msg, {**Any_Source_Errors, **source.get_non_retryable_errors()})
class TestSnowflakeValidateCredentials: