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): make row tracking survive redis and billing blips (#104528)

Tom Owers203cb11c4638
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index c1aa99db747a..4e77febcc599 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -278,14 +278,29 @@ def _raise_for_organization_error(res: requests.Response, *, map_not_found: bool
raise BillingQueryRejected()
+class BillingServiceResponseError(Exception):
+ """Billing answered with a status code the caller does not accept."""
+
+ def __init__(self, status_code: int, body: Any) -> None:
+ # The message and the body keep the positions callers already read: see
+ # `_raise_billing_error` in ee/api/billing.py, which parses the status out of the message.
+ super().__init__(f"Billing service returned bad status code: {status_code}", "body:", body)
+ self.status_code = status_code
+ self.body = body
+
+
def handle_billing_service_error(res: requests.Response, valid_codes=(200, 201, 404, 401)) -> None:
if res.status_code not in valid_codes:
logger.error(f"Billing service returned bad status code: {res.status_code}, body: {res.text}")
try:
- response = res.json()
- raise Exception(f"Billing service returned bad status code: {res.status_code}", f"body:", response)
+ body: Any = res.json()
except JSONDecodeError:
- raise Exception(f"Billing service returned bad status code: {res.status_code}", f"body:", res.text)
+ # A body that is not JSON, such as the empty body of a proxy timeout, is still the
+ # answer the caller has to report. Read it as text, so the decode failure does not
+ # become the reported cause of the error.
+ body = res.text
+
+ raise BillingServiceResponseError(res.status_code, body)
def _parse_funding_status(data: object) -> OrganizationFundingStatus:
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.py
index 8c35d76db3e5..d11ff667c4a5 100644
--- a/posthog/settings/data_warehouse.py
+++ b/posthog/settings/data_warehouse.py
@@ -145,8 +145,13 @@ GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY: str | None = os.getenv("GOOGLE_SHEETS
GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID: str | None = os.getenv("GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID")
GOOGLE_SHEETS_SERVICE_ACCOUNT_TOKEN_URI: str | None = os.getenv("GOOGLE_SHEETS_SERVICE_ACCOUNT_TOKEN_URI")
+# Only a local setup has a Redis on localhost. In a deployed environment nothing listens there,
+# so an environment that sets neither of these turned every warehouse Redis call into a connection
+# error. Leave the host unset instead, which lets the callers fall back to the shared REDIS_URL or
+# say that the feature is not configured.
+_DEFAULT_DATA_WAREHOUSE_REDIS_HOST = "localhost" if DEBUG or TEST else None
DATA_WAREHOUSE_REDIS_HOST: str | None = os.getenv(
- "DATA_WAREHOUSE_REDIS_HOST", os.getenv("POSTHOG_REDIS_HOST", "localhost")
+ "DATA_WAREHOUSE_REDIS_HOST", os.getenv("POSTHOG_REDIS_HOST", _DEFAULT_DATA_WAREHOUSE_REDIS_HOST)
)
DATA_WAREHOUSE_REDIS_PORT: str | None = os.getenv("DATA_WAREHOUSE_REDIS_PORT", os.getenv("POSTHOG_REDIS_PORT", "6379"))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
index 1f2116f7b110..c72c7231acd3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
@@ -1,8 +1,9 @@
import uuid
import asyncio
+from collections.abc import Awaitable, Callable
from contextlib import asynccontextmanager
from datetime import UTC, datetime
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, TypeVar
from django.conf import settings
from django.db.models import F, Q, Sum
@@ -16,6 +17,7 @@ from redis import (
exceptions as redis_exceptions,
)
from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from posthog.cloud_utils import get_cached_instance_license
from posthog.exceptions_capture import capture_exception
@@ -34,37 +36,88 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
+T = TypeVar("T")
+
+# A connect blip, a "too many open files" refusal and a replica redirect during a failover all
+# clear on their own, usually inside a second. Row tracking runs inside the import that calls it,
+# so the retry stays short: the import waits for every attempt.
+_retry_transient_redis_errors = retry(
+ retry=retry_if_exception_type(
+ (
+ redis_exceptions.ConnectionError,
+ redis_exceptions.TimeoutError,
+ redis_exceptions.ReadOnlyError,
+ )
+ ),
+ stop=stop_after_attempt(3),
+ wait=wait_exponential_jitter(initial=0.1, max=1),
+ reraise=True,
+)
+
def _get_hash_key(team_id: int) -> str:
return f"posthog:data_warehouse_row_tracking:{team_id}"
+def _redis_url() -> str | None:
+ """The dedicated warehouse Redis, or the shared one when no dedicated instance is configured.
+
+ The fallback used to be localhost. Nothing listens there in a deployed environment, so an
+ environment that sets neither DATA_WAREHOUSE_REDIS_HOST nor POSTHOG_REDIS_HOST turned every
+ row-tracking call into a connection error. The shared Redis is the same fallback the other
+ per-product instances take (see SESSION_RECORDING_REDIS_URL), and settings refuse to start
+ without it, so a genuinely unconfigured install fails at startup instead of here.
+ """
+ if settings.DATA_WAREHOUSE_REDIS_HOST and settings.DATA_WAREHOUSE_REDIS_PORT:
+ return f"redis://{settings.DATA_WAREHOUSE_REDIS_HOST}:{settings.DATA_WAREHOUSE_REDIS_PORT}/"
+
+ return settings.REDIS_URL or None
+
+
+async def _fail_open(description: str, command: Callable[[], Awaitable[T]], fallback: T) -> T:
+ """Run a row-tracking Redis command, retry a transient failure, then return `fallback`.
+
+ Row tracking is bookkeeping for the billing estimate, so no Redis failure may reach the import
+ that called it. A retried command runs twice if Redis applied the first attempt and the reply
+ was lost, which at most counts one batch of rows twice until the next sync resets the counter.
+ """
+ try:
+ return await _retry_transient_redis_errors(command)()
+ except redis_exceptions.RedisError as e:
+ await logger.awarning(f"Redis error while {description}, failing open", error=str(e))
+ return fallback
+
+
@asynccontextmanager
async def _get_redis():
"""Returns an async Redis client for row tracking operations."""
redis = None
- try:
- if not settings.DATA_WAREHOUSE_REDIS_HOST or not settings.DATA_WAREHOUSE_REDIS_PORT:
- raise Exception(
- "Missing env vars for dwh row tracking: DATA_WAREHOUSE_REDIS_HOST or DATA_WAREHOUSE_REDIS_PORT"
- )
+ url = _redis_url()
- redis = get_async_client(f"redis://{settings.DATA_WAREHOUSE_REDIS_HOST}:{settings.DATA_WAREHOUSE_REDIS_PORT}/")
- await redis.ping()
- except redis_exceptions.RedisError as e:
- # Row tracking already fails open when redis is unavailable (every caller
- # checks `if not redis: return`), so a Redis-side blip - unreachable, refusing
- # writes because RDB snapshotting failed, loading, etc. - isn't a bug, and
- # shouldn't be reported to error tracking. Same rationale as the RedisError
- # handling in will_hit_billing_limit below.
- await logger.awarning("Redis error while getting row tracking client, failing open", error=str(e))
- redis = None
- except Exception as e:
- capture_exception(e)
- # get_async_client only builds a lazy client, so a failed ping means redis is
- # still unreachable - reset it to None so callers' `if not redis: return` guard
- # actually skips the real command instead of raising the same error uncaught.
- redis = None
+ if url is None:
+ await logger.aerror("No Redis is configured for row tracking, failing open")
+ else:
+ try:
+ client = get_async_client(url)
+
+ async def _ping() -> None:
+ await client.ping()
+
+ # get_async_client only builds a lazy client, so the ping is the first real connection
+ # attempt. Hand the client to the caller only once it answers, so that a caller's
+ # `if not redis: return` guard skips the real command instead of raising the same
+ # error uncaught.
+ await _retry_transient_redis_errors(_ping)()
+ redis = client
+ except redis_exceptions.RedisError as e:
+ # Row tracking already fails open when redis is unavailable (every caller
+ # checks `if not redis: return`), so a Redis-side blip - unreachable, refusing
+ # writes because RDB snapshotting failed, loading, etc. - isn't a bug, and
+ # shouldn't be reported to error tracking. Same rationale as the RedisError
+ # handling in will_hit_billing_limit below.
+ await logger.awarning("Redis error while getting row tracking client, failing open", error=str(e))
+ except Exception as e:
+ capture_exception(e)
yield redis
@@ -74,15 +127,11 @@ async def setup_row_tracking(team_id: int, schema_id: uuid.UUID | str) -> None:
if not redis:
return
- try:
+ async def _command() -> None:
await redis.hset(_get_hash_key(team_id), str(schema_id), 0)
await redis.expire(_get_hash_key(team_id), 60 * 60 * 24 * 7) # 7 day expire
- except redis_exceptions.RedisError as e:
- # Same rationale as _get_redis above: a successful ping doesn't guarantee a
- # later command succeeds (e.g. Redis refusing writes because it can't persist
- # an RDB snapshot, or a replica failover). That's a transient infra blip, not
- # a bug, so it fails open without being reported to error tracking.
- await logger.awarning("Redis error while setting up row tracking, failing open", error=str(e))
+
+ await _fail_open("setting up row tracking", _command, None)
async def increment_rows(team_id: int, schema_id: uuid.UUID | str, rows: int) -> None:
@@ -90,10 +139,10 @@ async def increment_rows(team_id: int, schema_id: uuid.UUID | str, rows: int) ->
if not redis:
return
- try:
+ async def _command() -> None:
await redis.hincrby(_get_hash_key(team_id), str(schema_id), rows)
- except redis_exceptions.RedisError as e:
- await logger.awarning("Redis error while incrementing row tracking, failing open", error=str(e))
+
+ await _fail_open("incrementing row tracking", _command, None)
async def decrement_rows(team_id: int, schema_id: uuid.UUID | str, rows: int) -> None:
@@ -101,7 +150,7 @@ async def decrement_rows(team_id: int, schema_id: uuid.UUID | str, rows: int) ->
if not redis:
return
- try:
+ async def _command() -> None:
if not await redis.hexists(_get_hash_key(team_id), str(schema_id)):
return
@@ -114,8 +163,8 @@ async def decrement_rows(team_id: int, schema_id: uuid.UUID | str, rows: int) ->
await redis.hset(_get_hash_key(team_id), str(schema_id), 0)
else:
await redis.hincrby(_get_hash_key(team_id), str(schema_id), -rows)
- except redis_exceptions.RedisError as e:
- await logger.awarning("Redis error while decrementing row tracking, failing open", error=str(e))
+
+ await _fail_open("decrementing row tracking", _command, None)
async def finish_row_tracking(team_id: int, schema_id: uuid.UUID | str) -> None:
@@ -123,10 +172,10 @@ async def finish_row_tracking(team_id: int, schema_id: uuid.UUID | str) -> None:
if not redis:
return
- try:
+ async def _command() -> None:
await redis.hdel(_get_hash_key(team_id), str(schema_id))
- except redis_exceptions.RedisError as e:
- await logger.awarning("Redis error while finishing row tracking, failing open", error=str(e))
+
+ await _fail_open("finishing row tracking", _command, None)
async def get_rows(team_id: int, schema_id: uuid.UUID | str) -> int:
@@ -134,15 +183,15 @@ async def get_rows(team_id: int, schema_id: uuid.UUID | str) -> int:
if not redis:
return 0
- try:
+ async def _command() -> int:
if await redis.hexists(_get_hash_key(team_id), str(schema_id)):
value = await redis.hget(_get_hash_key(team_id), str(schema_id))
if value:
return int(value)
- except redis_exceptions.RedisError as e:
- await logger.awarning("Redis error while reading row tracking, failing open", error=str(e))
- return 0
+ return 0
+
+ return await _fail_open("reading row tracking", _command, 0)
async def get_all_rows_for_team(team_id: int) -> int:
@@ -150,12 +199,11 @@ async def get_all_rows_for_team(team_id: int) -> int:
if not redis:
return 0
- try:
+ async def _command() -> int:
pairs = await redis.hgetall(_get_hash_key(team_id))
return sum(int(v) for v in pairs.values())
- except redis_exceptions.RedisError as e:
- await logger.awarning("Redis error while reading team row tracking, failing open", error=str(e))
- return 0
+
+ return await _fail_open("reading team row tracking", _command, 0)
# The billing-period sum only moves when a job completes, so serving it from a cache for a
@@ -177,10 +225,11 @@ def _get_sync_redis() -> Redis | None:
The cache is read inside the same database thread as the query it replaces, so it uses the
synchronous client rather than the async one the row-tracking helpers use.
"""
- if not settings.DATA_WAREHOUSE_REDIS_HOST or not settings.DATA_WAREHOUSE_REDIS_PORT:
+ url = _redis_url()
+ if url is None:
return None
- return get_client(f"redis://{settings.DATA_WAREHOUSE_REDIS_HOST}:{settings.DATA_WAREHOUSE_REDIS_PORT}/")
+ return get_client(url)
def _rows_synced_in_billing_period(
@@ -230,6 +279,37 @@ def _rows_synced_in_billing_period(
return rows_synced_in_billing_period
+# Billing answers a request it could not finish in time with a 408, and a request it could not
+# serve with a 5xx. Both clear on a retry, and the check runs once per sync, so a few seconds of
+# retry is cheaper than a sync that skips the limit.
+_TRANSIENT_BILLING_STATUS_CODES = frozenset({408, 429, 500, 502, 503, 504})
+
+
+def _is_transient_billing_error(error: BaseException) -> bool:
+ # A connect failure or a read timeout clears on its own. `RequestException` also covers a
+ # permanently broken request, such as an invalid `BILLING_SERVICE_URL`, and that must not be
+ # retried: it fails the same way on every attempt, so retrying only adds backoff to every sync.
+ if isinstance(error, requests.exceptions.ConnectionError | requests.exceptions.Timeout):
+ return True
+
+ # BillingServiceResponseError carries the status code billing answered with. The status is
+ # read through getattr because ee is not importable in every deployment.
+ return getattr(error, "status_code", None) in _TRANSIENT_BILLING_STATUS_CODES
+
+
+_retry_transient_billing_errors = retry(
+ retry=retry_if_exception(_is_transient_billing_error),
+ stop=stop_after_attempt(3),
+ wait=wait_exponential_jitter(initial=0.5, max=4),
+ reraise=True,
+)
+
+
+@_retry_transient_billing_errors
+async def _fetch_billing_data(get_billing_data: Callable[[], Awaitable[T]]) -> T:
+ return await get_billing_data()
+
+
async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", logger: FilteringBoundLogger) -> bool:
if not EE_AVAILABLE:
return False
@@ -287,7 +367,7 @@ async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", log
billing_res,
current_billing_cycle_start,
rows_synced_in_billing_period,
- ) = await _get_billing_data()
+ ) = await _fetch_billing_data(_get_billing_data)
await logger.adebug(f"BillingLimits: Organisation_id = {org_id}")
await logger.adebug(f"BillingLimits: Teams in org: {all_teams_in_org}")
@@ -350,6 +430,14 @@ async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", log
return False
except Exception as e:
+ if _is_transient_billing_error(e):
+ # Billing refused with a status that clears on its own, and the retries above are
+ # spent. The check already fails open, so this is infrastructure noise rather than a
+ # bug to report to error tracking.
+ await logger.awarning(f"BillingLimits: billing service is unavailable, failing open: {e}")
+
+ return False
+
await logger.adebug(f"BillingLimits: Failed with exception {e}")
capture_exception(e)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py
index dbf883bcc9a0..69b0be288981 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_row_tracking.py
@@ -19,20 +19,46 @@ from redis import exceptions as redis_exceptions
from structlog.types import FilteringBoundLogger
from posthog.models import Team
-from posthog.redis import get_client
+from posthog.redis import get_async_client, get_client
from posthog.sync import database_sync_to_async
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import (
_get_redis,
+ decrement_rows,
finish_row_tracking,
+ get_all_rows_for_team,
+ get_rows,
increment_rows,
setup_row_tracking,
will_hit_billing_limit,
)
_READ_ONLY_REPLICA_ERROR = redis_exceptions.ReadOnlyError("You can't write against a read only replica.")
+_MISCONF_ERROR = redis_exceptions.ResponseError(
+ "MISCONF Redis is configured to save RDB snapshots, but it's currently unable to persist to disk. "
+ "Commands that may modify the data set are disabled, because this instance is configured to report "
+ "errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check "
+ "the Redis logs for details about the RDB error."
+)
+
+# Every row-tracking entry point the import calls, with the value it must return when Redis refuses
+# every command.
+_ENTRY_POINTS = [
+ ("setup_row_tracking", lambda team_id, schema_id: setup_row_tracking(team_id, schema_id), None),
+ ("increment_rows", lambda team_id, schema_id: increment_rows(team_id, schema_id, 10), None),
+ ("decrement_rows", lambda team_id, schema_id: decrement_rows(team_id, schema_id, 10), None),
+ ("finish_row_tracking", lambda team_id, schema_id: finish_row_tracking(team_id, schema_id), None),
+ ("get_rows", lambda team_id, schema_id: get_rows(team_id, schema_id), 0),
+ ("get_all_rows_for_team", lambda team_id, _schema_id: get_all_rows_for_team(team_id), 0),
+]
+
+_FAIL_OPEN_CASES = [
+ (f"{entry_point_name}_{error_name}", call, fallback, error)
+ for entry_point_name, call, fallback in _ENTRY_POINTS
+ for error_name, error in [("read_only_replica", _READ_ONLY_REPLICA_ERROR), ("misconf", _MISCONF_ERROR)]
+]
class _CacheReadFailsClient:
@@ -46,6 +72,22 @@ class _CacheReadFailsClient:
raise redis_exceptions.ConnectionError("Error connecting to redis:6379.")
+class _FirstIncrementFailsClient:
+ def __init__(self, inner):
+ self._inner = inner
+ self._remaining_failures = 1
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ async def hincrby(self, *args, **kwargs):
+ if self._remaining_failures:
+ self._remaining_failures -= 1
+ raise redis_exceptions.ConnectionError("Error connecting to redis:6379.")
+
+ return await self._inner.hincrby(*args, **kwargs)
+
+
class TestRowTrackingRedisUnavailable(BaseTest):
@parameterized.expand(
[
@@ -92,68 +134,70 @@ class TestRowTrackingRedisUnavailable(BaseTest):
unreachable_client.hset.assert_not_called()
mock_capture_exception.assert_not_called()
- @parameterized.expand(
- [
- (
- "misconf_error",
- redis_exceptions.ResponseError(
- "MISCONF Redis is configured to save RDB snapshots, but it's currently "
- "unable to persist to disk. Commands that may modify the data set are "
- "disabled, because this instance is configured to report errors during "
- "writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). "
- "Please check the Redis logs for details about the RDB error."
- ),
- ),
- ("read_only_replica_error", _READ_ONLY_REPLICA_ERROR),
- ]
- )
+ @parameterized.expand(_FAIL_OPEN_CASES)
@pytest.mark.asyncio
- async def test_setup_row_tracking_does_not_raise_or_capture_when_redis_rejects_writes(self, _name, exception):
- # A successful ping doesn't guarantee the following command succeeds - e.g. Redis
- # can refuse writes (MISCONF, or a replica redirect during failover). That must
- # fail open like the unreachable-at-ping case above: no crash, and (since it's a
- # transient infra blip the caller already tolerates) no error-tracking report.
- read_only_client = mock.AsyncMock()
- read_only_client.ping.return_value = True
- read_only_client.hset.side_effect = exception
+ async def test_row_tracking_fails_open_when_redis_refuses_every_command(self, _name, call, fallback, exception):
+ # A successful ping doesn't guarantee the following command succeeds: Redis can refuse a
+ # write because it can't persist an RDB snapshot, and a failover can point the client at a
+ # read only replica. Row tracking is bookkeeping for the import that calls it, so no
+ # command may raise into that import, and a transient infra blip is not worth an
+ # error-tracking issue.
+ refusing_client = mock.AsyncMock()
+ refusing_client.ping.return_value = True
+ for command in ("hset", "expire", "hincrby", "hdel", "hexists", "hget", "hgetall"):
+ getattr(refusing_client, command).side_effect = exception
with (
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.row_tracking.get_async_client",
- return_value=read_only_client,
+ return_value=refusing_client,
),
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.row_tracking.capture_exception"
) as mock_capture_exception,
override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"),
):
- await setup_row_tracking(self.team.pk, str(uuid.uuid4()))
+ assert await call(self.team.pk, str(uuid.uuid4())) == fallback
- read_only_client.expire.assert_not_called()
mock_capture_exception.assert_not_called()
@pytest.mark.asyncio
- async def test_finish_row_tracking_does_not_raise_or_capture_when_redis_rejects_writes(self):
- # Regression test: finish_row_tracking's hdel used to report a read-only-replica
- # error (e.g. during a Redis failover) to error tracking instead of failing open
- # like the rest of row tracking already does.
- read_only_client = mock.AsyncMock()
- read_only_client.ping.return_value = True
- read_only_client.hdel.side_effect = _READ_ONLY_REPLICA_ERROR
+ async def test_increment_rows_keeps_the_count_through_a_transient_failure(self):
+ # A single connection blip used to drop the increment, which makes the billing limit read
+ # a count that is short by one batch for the rest of the sync.
+ schema_id = str(uuid.uuid4())
+
+ with override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"):
+ await setup_row_tracking(self.team.pk, schema_id)
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.row_tracking.get_async_client",
+ side_effect=lambda url: _FirstIncrementFailsClient(get_async_client(url)),
+ ):
+ await increment_rows(self.team.pk, schema_id, 10)
+
+ assert await get_rows(self.team.pk, schema_id) == 10
+ await finish_row_tracking(self.team.pk, schema_id)
+
+ @pytest.mark.asyncio
+ async def test_row_tracking_uses_the_shared_redis_when_no_dedicated_host_is_configured(self):
+ # An unset host used to fall back to localhost:6379, where nothing listens in a deployed
+ # environment, so every row-tracking call raised a connection error.
with (
mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.row_tracking.get_async_client",
- return_value=read_only_client,
+ return_value=mock.AsyncMock(),
+ ) as mock_get_async_client,
+ override_settings(
+ DATA_WAREHOUSE_REDIS_HOST=None,
+ DATA_WAREHOUSE_REDIS_PORT=None,
+ REDIS_URL="redis://shared-redis.example.com:6379/",
),
- mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.row_tracking.capture_exception"
- ) as mock_capture_exception,
- override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"),
):
- await finish_row_tracking(self.team.pk, str(uuid.uuid4()))
+ await setup_row_tracking(self.team.pk, str(uuid.uuid4()))
- mock_capture_exception.assert_not_called()
+ mock_get_async_client.assert_called_once_with("redis://shared-redis.example.com:6379/")
@pytest.mark.timeout(600)
@@ -437,6 +481,38 @@ class TestRowTracking(BaseTest):
mock_capture_exception.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_row_tracking_retries_and_tolerates_a_transient_billing_refusal(self):
+ # Billing answers a request it could not finish in time with a 408 and an empty body.
+ # That must be retried, and once the retries are spent it must fail open quietly: the
+ # check already tolerates a missing answer, so it is not worth an error-tracking issue.
+ #
+ # The refusal is raised through `handle_billing_service_error` itself, on a response with
+ # no body, rather than by constructing `BillingServiceResponseError` directly: that is the
+ # only way to prove the real response-handling path is what attaches the `status_code`
+ # that `_is_transient_billing_error` reads.
+ from ee.billing.billing_manager import handle_billing_service_error
+
+ source = await self._create_source()
+
+ def _raise_billing_timeout(*args, **kwargs):
+ response = requests.Response()
+ response.status_code = 408
+ handle_billing_service_error(response)
+
+ with (
+ mock.patch("ee.billing.billing_manager.BillingManager.get_billing") as mock_get_billing,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.row_tracking.capture_exception"
+ ) as mock_capture_exception,
+ ):
+ mock_get_billing.side_effect = _raise_billing_timeout
+
+ assert await self._run(source, 10) is False
+
+ assert mock_get_billing.call_count == 3
+ mock_capture_exception.assert_not_called()
+
@pytest.mark.asyncio
async def test_row_tracking_fails_open_on_request_error_without_capturing_exception(self):
# A network blip (e.g. a proxy timeout) reaching the billing service is a transient