: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): let v3 lock redis calls propagate activity cancellation (#110481)
Tom Owersceb4ac586997
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/sync_lock.pyindex 9d0033e51ad8..a8fb01b95d83 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py@@ -1,4 +1,5 @@import json+import asynciofrom collections.abc import Generatorfrom contextlib import contextmanagerfrom datetime import UTC, datetime@@ -15,6 +16,18 @@ from posthog.redis import get_clientlogger = structlog.get_logger(__name__)++def _is_cancellation(error: BaseException) -> bool:+ """Whether `error` is an activity cancellation rather than a genuine Redis failure.++ Temporal can inject a `temporalio.exceptions.CancelledError` (an `Exception` subclass) into+ whatever line of this sync code is running when the calling activity is cancelled — e.g. mid+ socket read inside `redis_client.ping()`. Match on the type name too so it isn't mistaken for+ a genuine Redis failure if it ever arrives already wrapped.+ """+ return isinstance(error, asyncio.CancelledError) or type(error).__name__ == "CancelledError"++LOCK_KEY_PREFIX = "v3_pipeline_lock"# Holder metadata lives in a second key because the lock value must stay a bare# run-id token — every release path compares it byte-for-byte.@@ -69,6 +82,8 @@ def _get_redis_client() -> Generator[redis.Redis | None]:redis_client = get_client(f"redis://{settings.DATA_WAREHOUSE_REDIS_HOST}:{settings.DATA_WAREHOUSE_REDIS_PORT}/")_connect_and_ping(redis_client)except Exception as e:+ if _is_cancellation(e):+ raiselogger.exception("redis_unavailable_for_v3_pipeline_lock", error=str(e))capture_exception(e)redis_client = None@@ -94,6 +109,8 @@ def acquire_v3_pipeline_lock(team_id: int, schema_id: str, token: str) -> bool:acquired = client.set(_lock_key(team_id, schema_id), token, nx=True, ex=LOCK_TTL_SECONDS)return bool(acquired)except Exception as e:+ if _is_cancellation(e):+ raiselogger.exception("v3_pipeline_lock_acquire_error",error=str(e),@@ -120,6 +137,8 @@ def write_v3_pipeline_lock_meta(team_id: int, schema_id: str, run_id: str, workf)client.set(_lock_meta_key(team_id, schema_id), payload, ex=LOCK_TTL_SECONDS)except Exception as e:+ if _is_cancellation(e):+ raiselogger.warning("v3_pipeline_lock_meta_write_error", error=str(e), team_id=team_id, schema_id=schema_id)capture_exception(e)@@ -140,6 +159,8 @@ def get_v3_pipeline_lock_meta(team_id: int, schema_id: str) -> dict[str, Any] |return Nonereturn parsedexcept Exception as e:+ if _is_cancellation(e):+ raiselogger.warning("v3_pipeline_lock_meta_read_error", error=str(e), team_id=team_id, schema_id=schema_id)capture_exception(e)return None@@ -157,6 +178,8 @@ def get_v3_pipeline_lock_holder(team_id: int, schema_id: str) -> str | None:return Nonereturn holder.decode() if isinstance(holder, bytes) else str(holder)except Exception as e:+ if _is_cancellation(e):+ raiselogger.warning("v3_pipeline_lock_get_holder_error", error=str(e), team_id=team_id, schema_id=schema_id)capture_exception(e)return None@@ -174,6 +197,8 @@ def release_v3_pipeline_lock(team_id: int, schema_id: str, token: str) -> bool:)return bool(result)except Exception as e:+ if _is_cancellation(e):+ raiselogger.warning("v3_pipeline_lock_release_error", error=str(e), team_id=team_id, schema_id=schema_id)capture_exception(e)return Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.pyindex 38a60da0aa14..b9ce1dadb840 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.py@@ -2,6 +2,7 @@ import pytestfrom unittest.mock import MagicMock, patchimport redis+import temporalio.exceptionsfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (LOCK_TTL_SECONDS,@@ -54,6 +55,20 @@ class TestAcquireV3PipelineLock:assert acquire_v3_pipeline_lock(1, "s-1", "tok-1") is False+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock.capture_exception")+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock._get_redis_client")+ def test_propagates_activity_cancellation_instead_of_failing_closed(+ self, mock_ctx: MagicMock, mock_capture: MagicMock+ ) -> None:+ mock_redis = MagicMock()+ mock_redis.set.side_effect = temporalio.exceptions.CancelledError()+ mock_ctx.return_value.__enter__ = MagicMock(return_value=mock_redis)+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)++ with pytest.raises(temporalio.exceptions.CancelledError):+ acquire_v3_pipeline_lock(1, "s-1", "tok-1")+ mock_capture.assert_not_called()+class TestGetV3PipelineLockHolder:@pytest.mark.parametrize(@@ -126,6 +141,20 @@ class TestReleaseV3PipelineLock:assert release_v3_pipeline_lock(1, "s-1", "tok-1") is False+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock.capture_exception")+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock._get_redis_client")+ def test_propagates_activity_cancellation_instead_of_failing_silently(+ self, mock_ctx: MagicMock, mock_capture: MagicMock+ ) -> None:+ mock_redis = MagicMock()+ mock_redis.eval.side_effect = temporalio.exceptions.CancelledError()+ mock_ctx.return_value.__enter__ = MagicMock(return_value=mock_redis)+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)++ with pytest.raises(temporalio.exceptions.CancelledError):+ release_v3_pipeline_lock(1, "s-1", "tok-1")+ mock_capture.assert_not_called()+class TestGetRedisClient:"""The acquire/release activities run with a single Temporal attempt, so a bare@@ -150,3 +179,17 @@ class TestGetRedisClient:with _get_redis_client() as client:assert client is Noneassert mock_redis.ping.call_count == 3++ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock.capture_exception")+ @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock.get_client")+ def test_propagates_activity_cancellation_instead_of_failing_closed(+ self, mock_get_client: MagicMock, mock_capture: MagicMock+ ) -> None:+ mock_redis = MagicMock()+ mock_redis.ping.side_effect = temporalio.exceptions.CancelledError()+ mock_get_client.return_value = mock_redis++ with pytest.raises(temporalio.exceptions.CancelledError):+ with _get_redis_client():+ pass+ mock_capture.assert_not_called()