:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-imports): stop reporting the executor-shutdown race in the queue unlock retry (#114770)
Tom Owers11642a6b11bc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex 1b8297f52ec7..c15844a82923 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -49,6 +49,7 @@ from products.warehouse_sources_queue.backend.core.batch_consumer import (_is_admin_shutdown_error,_is_connect_timeout_error,_is_dns_resolution_transient_error,+ _is_executor_shutdown_error,_is_retryable_queue_db_error,_is_schema_lag_error,_is_server_not_ready_error,@@ -1601,6 +1602,44 @@ def test_is_server_not_ready_error_ignores_non_operational_errors():assert _is_server_not_ready_error(RuntimeError("the database system is in recovery mode")) is False+class TestExecutorShutdownErrorClassification:+ def test_classifies_executor_shutdown(self) -> None:+ assert _is_executor_shutdown_error(RuntimeError("cannot schedule new futures after shutdown")) is True++ def test_ignores_other_runtime_errors(self) -> None:+ assert _is_executor_shutdown_error(RuntimeError("some other failure")) is False++ @pytest.mark.asyncio+ async def test_unlock_group_does_not_report_executor_shutdown_error(self) -> None:+ # Reproduces the reported issue: the group's per-group connection is left mid-protocol+ # by the task's own cancellation, so the first unlock attempt fails with an+ # OperationalError and _unlock_group falls back to a fresh connection. If the pod is+ # already mid-teardown, that redial hits the event loop's already-shut-down default+ # executor (used for DNS resolution) instead of a connection error, and must not page+ # anyone — the lease simply expires and a surviving pod reclaims it.+ consumer = _make_consumer()+ batches = [_make_batch()]++ with (+ patch.object(+ consumer._adapter,+ "unlock",+ new_callable=AsyncMock,+ side_effect=psycopg.OperationalError("another command is already in progress"),+ ),+ patch.object(+ consumer,+ "_connect",+ new_callable=AsyncMock,+ side_effect=RuntimeError("cannot schedule new futures after shutdown"),+ ),+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,+ ):+ await consumer._unlock_group(_make_healthy_conn(), batches, team_id=1, schema_id="schema-1")++ mock_capture.assert_not_called()++class TestPollFailureLiveness:def test_withholds_liveness_after_threshold_consecutive_failures(self):# Without the trip, a pod whose every poll fails passes liveness forever.diff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.pyindex 374f2efb5ef5..d89abf302e07 100644--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py@@ -201,6 +201,20 @@ def _is_pooler_login_retry_cached_error(error: BaseException) -> bool:return _POOLER_LOGIN_RETRY_CACHED_ERROR_MARKER in str(error).lower()+# asyncio's default executor (what ``loop.run_in_executor(None, ...)`` submits to -- psycopg+# uses it for DNS resolution while connecting) is shut down once the running event loop winds+# down. ``_unlock_group``'s retry-connect runs in a group task's ``finally`` block: that task+# can still be executing it after ``_close()``'s drain window elapsed and gave up waiting,+# because the task's own cancellation left the shared per-group connection mid-protocol and+# triggered the retry in the first place. By then the pod is already exiting, so there is+# nothing a redial could reach; the lease simply expires and a surviving pod reclaims it.+_EXECUTOR_SHUTDOWN_ERROR_MARKER = "cannot schedule new futures after shutdown"+++def _is_executor_shutdown_error(error: BaseException) -> bool:+ return isinstance(error, RuntimeError) and _EXECUTOR_SHUTDOWN_ERROR_MARKER in str(error).lower()++def _is_transient_queue_db_error(error: BaseException) -> bool:"""Whether `error` is the queue DB being briefly unavailable rather than a bug.@@ -698,7 +712,7 @@ class BatchConsumer:through the poll-failure liveness trip and the queue-freshness gauge, which measurethe outage rather than counting its exceptions."""- if _is_transient_queue_db_error(error):+ if _is_transient_queue_db_error(error) or _is_executor_shutdown_error(error):logger.warning(event, error=str(error), **context)returnlogger.exception(event, **context)