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(warehouse-sources): stop free in-flight rows blocking billable syncs (#114424)

Daniel RCb62cab3377e4
diff --git a/products/warehouse_sources/backend/billing.py b/products/warehouse_sources/backend/billing.py
index c3b70abdf3fc..acd4c691d052 100644
--- a/products/warehouse_sources/backend/billing.py
+++ b/products/warehouse_sources/backend/billing.py
@@ -28,6 +28,10 @@ FREE_PERIOD_START = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)
FREE_PERIOD_END = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)
+def is_in_free_historical_window(source_created_at: datetime) -> bool:
+ return source_created_at >= datetime.now(UTC) - FREE_HISTORICAL_WINDOW
+
+
def billed_usage_for_job(job: ExternalDataJob) -> tuple[str, int] | None:
"""The meter and row count one finished job bills, or None if it bills nothing.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 32f47930a86b..9247688e4fc9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -18,6 +18,7 @@ from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.errors import NonReportableError
from posthog.utils import get_machine_id
+from products.warehouse_sources.backend.billing import is_in_free_historical_window
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import get_incremental_field_value
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
DUPLICATE_PRIMARY_KEYS_ERROR,
@@ -32,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import (
decrement_rows,
increment_rows,
+ setup_row_tracking,
will_hit_billing_limit,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.primary_keys import resolve_merge_keys
@@ -492,14 +494,17 @@ async def setup_row_tracking_with_billing_check(
logger: FilteringBoundLogger,
billable: bool | None = True,
) -> None:
- if resource.rows_to_sync:
- await increment_rows(team_id, schema.id, resource.rows_to_sync)
- # Check billing limits against incoming rows (skip for non-billable jobs)
- if billable and await will_hit_billing_limit(team_id=team_id, source=source, logger=logger):
- raise BillingLimitsWillBeReachedException(
- f"Your account will hit your Data Warehouse billing limits syncing {resource.name} "
- f"with {resource.rows_to_sync} rows"
- )
+ # The limit check sums these rows over every running sync in the organization. A run the check skips (a
+ # non-billable job, or a source in its free first week at the start) must stay out, or it blocks the others.
+ if not resource.rows_to_sync or not billable or is_in_free_historical_window(source.created_at):
+ return
+
+ await increment_rows(team_id, schema.id, resource.rows_to_sync)
+ if await will_hit_billing_limit(team_id=team_id, source=source, logger=logger):
+ raise BillingLimitsWillBeReachedException(
+ f"Your account will hit your Data Warehouse billing limits syncing {resource.name} "
+ f"with {resource.rows_to_sync} rows"
+ )
def reset_pipeline_requested(
@@ -787,6 +792,9 @@ async def handle_corrupted_delta_log(
if job.billable:
job.billable = False
await database_sync_to_async_pool(job.save)(update_fields=["billable"])
+ # The run registered its row estimate while the job was still billable. The estimate must
+ # stop counting toward the limit check, the same as for a job that starts non-billable.
+ await setup_row_tracking(schema.team_id, schema.id)
_capture_delta_revived(schema, job, outcome="reset_rebuild", made_non_billable=was_billable)
await logger.awarning(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
index 483032ffbc52..0d6d3f3d1878 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
@@ -6,6 +6,8 @@ import pytest
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.test import override_settings
+
import pyarrow as pa
from asgiref.sync import async_to_sync
from parameterized import parameterized
@@ -44,6 +46,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.e
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
MissingPrimaryKeysException,
)
+from products.warehouse_sources.backend.temporal.data_imports.row_tracking import (
+ finish_row_tracking,
+ get_rows,
+ increment_rows,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException
from products.warehouse_sources.backend.types import IncrementalFieldType
@@ -513,13 +520,21 @@ class TestHandleCorruptedDeltaLog:
schema, job = self._schema_and_job(team) # sync_type_config has no repartition_swap → no salvage path
helper = MagicMock(is_table_corrupted=AsyncMock(return_value=True), reset_table=AsyncMock())
- with patch(f"{_EXTRACT_MODULE}.posthoganalytics") as ph:
+ with (
+ patch(f"{_EXTRACT_MODULE}.posthoganalytics") as ph,
+ override_settings(DATA_WAREHOUSE_REDIS_HOST="localhost", DATA_WAREHOUSE_REDIS_PORT="6379"),
+ ):
+ # The run registers its row estimate before the corruption check, while it is still billable.
+ async_to_sync(increment_rows)(team.pk, schema.id, 20)
result = async_to_sync(handle_corrupted_delta_log)(schema, job, helper, self._logger())
+ rows_counted_toward_the_limit = async_to_sync(get_rows)(team.pk, schema.id)
+ async_to_sync(finish_row_tracking)(team.pk, schema.id)
assert result is True
helper.reset_table.assert_awaited_once()
job.refresh_from_db()
assert job.billable is False
+ assert rows_counted_toward_the_limit == 0
# A revival must be observable, tagged with how it recovered and that the rebuild was made non-billable.
assert ph.capture.call_args.kwargs["event"] == "warehouse_delta_revived"
assert ph.capture.call_args.kwargs["properties"]["outcome"] == "reset_rebuild"
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 c72c7231acd3..94cc495db019 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
@@ -27,7 +27,12 @@ from posthog.settings import EE_AVAILABLE
from posthog.settings.base_variables import TEST
from posthog.sync import database_sync_to_async_pool
-from products.warehouse_sources.backend.billing import FREE_HISTORICAL_WINDOW, FREE_PERIOD_END, FREE_PERIOD_START
+from products.warehouse_sources.backend.billing import (
+ FREE_HISTORICAL_WINDOW,
+ FREE_PERIOD_END,
+ FREE_PERIOD_START,
+ is_in_free_historical_window,
+)
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob, billable_destination_multiplier
if TYPE_CHECKING:
@@ -320,7 +325,7 @@ async def will_hit_billing_limit(team_id: int, source: "ExternalDataSource", log
await logger.adebug("Running will_hit_billing_limit")
# Handle free period for newly created data sources
- if source.created_at >= datetime.now(UTC) - FREE_HISTORICAL_WINDOW:
+ if is_in_free_historical_window(source.created_at):
await logger.ainfo(
f"Skipping billing limits check for newly created data source for 7-days free rows. source.created_at = {source.created_at}"
)
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 69b0be288981..1174263dbbd6 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
@@ -23,7 +23,14 @@ 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_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
+ setup_row_tracking_with_billing_check,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
+ BillingLimitsWillBeReachedException,
+)
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import (
_get_redis,
decrement_rows,
@@ -34,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.row_tracking impor
setup_row_tracking,
will_hit_billing_limit,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
_READ_ONLY_REPLICA_ERROR = redis_exceptions.ReadOnlyError("You can't write against a read only replica.")
_MISCONF_ERROR = redis_exceptions.ResponseError(
@@ -254,7 +262,8 @@ class TestRowTracking(BaseTest):
if keys:
await redis.delete(*keys)
- async def _run(self, source: ExternalDataSource, limit: int, clear_cache: bool = True) -> bool:
+ @contextlib.asynccontextmanager
+ async def _billing_check_environment(self, limit: int, clear_cache: bool = True):
from ee.models.license import License
if clear_cache:
@@ -273,13 +282,31 @@ class TestRowTracking(BaseTest):
self._setup_limits(limit),
time_machine.travel("2024-01-01 12:00:00", tick=False),
):
+ yield
+
+ async def _run(self, source: ExternalDataSource, limit: int, clear_cache: bool = True) -> bool:
+ async with self._billing_check_environment(limit, clear_cache):
return await will_hit_billing_limit(team_id=self.team.pk, source=source, logger=self._logger())
@sync_to_async
- def _create_source(self) -> ExternalDataSource:
- with time_machine.travel(datetime(2023, 12, 1), tick=False):
+ def _create_source(self, created_at: datetime = datetime(2023, 12, 1)) -> ExternalDataSource:
+ with time_machine.travel(created_at, tick=False):
return ExternalDataSource.objects.create(team=self.team)
+ @sync_to_async
+ def _create_schema(self, source: ExternalDataSource) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(team=self.team, source=source, name=str(uuid.uuid4()))
+
+ async def _start_sync(self, schema: ExternalDataSchema, rows_to_sync: int, billable: bool = True) -> None:
+ await setup_row_tracking_with_billing_check(
+ self.team.pk,
+ schema,
+ SourceResponse(name=schema.name, items=lambda: [], primary_keys=None, rows_to_sync=rows_to_sync),
+ schema.source,
+ self._logger(),
+ billable=billable,
+ )
+
@pytest.mark.asyncio
async def test_row_tracking(self):
source = await self._create_source()
@@ -363,6 +390,33 @@ class TestRowTracking(BaseTest):
async with self._setup_redis_rows(20):
assert await self._run(source, 10) is True
+ @parameterized.expand(
+ [
+ ("non_billable_run", False, datetime(2023, 12, 1), False),
+ ("run_of_a_source_in_its_free_week", True, datetime(2023, 12, 30), False),
+ ("billable_run", True, datetime(2023, 12, 1), True),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_in_flight_rows_count_toward_the_limit_only_when_they_will_bill(
+ self, _name, in_flight_billable, in_flight_source_created_at, blocks_the_next_sync
+ ):
+ in_flight_schema = await self._create_schema(await self._create_source(in_flight_source_created_at))
+ next_schema = await self._create_schema(await self._create_source())
+
+ async with self._billing_check_environment(limit=25):
+ try:
+ await self._start_sync(in_flight_schema, rows_to_sync=20, billable=in_flight_billable)
+
+ if blocks_the_next_sync:
+ with pytest.raises(BillingLimitsWillBeReachedException):
+ await self._start_sync(next_schema, rows_to_sync=10)
+ else:
+ await self._start_sync(next_schema, rows_to_sync=10)
+ finally:
+ await finish_row_tracking(self.team.pk, in_flight_schema.id)
+ await finish_row_tracking(self.team.pk, next_schema.id)
+
@pytest.mark.asyncio
async def test_row_tracking_with_previous_rows_from_other_team_in_org(self):
another_team = await sync_to_async(Team.objects.create)(organization=self.organization)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py
index 1606d885cc9c..8e9d24088753 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/check_billing_limits.py
@@ -14,7 +14,7 @@ from posthog.models.team.team import Team
from posthog.settings.base_variables import TEST
from posthog.temporal.common.logger import get_logger
-from products.warehouse_sources.backend.billing import FREE_HISTORICAL_WINDOW, FREE_PERIOD_END, FREE_PERIOD_START
+from products.warehouse_sources.backend.billing import FREE_PERIOD_END, FREE_PERIOD_START, is_in_free_historical_window
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.util import with_internal_db_retries
@@ -62,7 +62,7 @@ def billing_limit_reached(
logger.info("Skipping billing limits check for non-billable job")
return False
- if source.created_at >= datetime.now(UTC) - FREE_HISTORICAL_WINDOW:
+ if is_in_free_historical_window(source.created_at):
logger.info(
f"Skipping billing limits check for newly created data source for 7-days free rows. source.created_at = {source.created_at}"
)