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.

feat(usage): collect warehouse, batch export and replay vision usage (#89875)

Ben Whitef0e04be850c7
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 6111d447998d..535806b77e28 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -7,7 +7,7 @@ import logging
import dataclasses
from collections import Counter, defaultdict
from collections.abc import Callable, Sequence
-from datetime import UTC, datetime, timedelta
+from datetime import datetime, timedelta
from typing import Any, Literal, Optional, TypedDict, Union
from django.conf import settings
@@ -75,9 +75,12 @@ from products.tasks.backend.facade.billing import (
get_billable_sandbox_compute_usage_by_team,
get_task_sandbox_usage_by_team,
)
-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataJob, ExternalDataSchema
+from products.warehouse_sources.backend.facade.billing import (
+ get_free_historical_rows_synced_by_team,
+ get_rows_synced_by_team,
+)
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema
from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus
-from products.warehouse_sources.backend.models.external_data_job import billable_destination_multiplier
logger = structlog.get_logger(__name__)
logging.getLogger(__name__).setLevel(logging.INFO)
@@ -2088,64 +2091,16 @@ def combine_posthog_code_credits(token_credits: int, compute_credits: int) -> in
return token_credits + compute_credits
-dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)
-dwh_pricing_free_period_end = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)
-
-# A source's first week of syncing is free.
-NEW_SOURCE_FREE_WINDOW = timedelta(days=7)
-
-
-def _rows_synced_totals(
- begin: datetime,
- end: datetime,
- source_age: Literal["any", "new_only", "established_only"],
-) -> list:
- """Rows synced per team, counted once per destination the run delivered to.
-
- A run is complete only once every destination has taken every batch, so multiplying by
- the destination count snapshotted on the run is exact. Runs that predate destinations
- carry a count of 1 and bill exactly as they did before.
- """
- filters = Q(
- finished_at__gte=begin,
- finished_at__lte=end,
- billable=True,
- status=ExternalDataJob.Status.COMPLETED,
- )
-
- if source_age != "any":
- is_new = Q(pipeline__created_at__gte=end - NEW_SOURCE_FREE_WINDOW)
- filters &= is_new if source_age == "new_only" else ~is_new
-
- return list(
- ExternalDataJob.objects.filter(filters)
- .values("team_id")
- .annotate(total=Sum(F("rows_synced") * billable_destination_multiplier()))
- )
-
-
@timed_log()
@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
def get_teams_with_rows_synced_in_period(begin: datetime, end: datetime) -> list:
- if begin >= dwh_pricing_free_period_start and begin < dwh_pricing_free_period_end:
- # during the free period, everyone gets free rows synced
- return []
-
- if begin >= dwh_pricing_free_period_end:
- # after the free period, don't include rows reported in the free historical period
- return _rows_synced_totals(begin, end, source_age="established_only")
-
- return _rows_synced_totals(begin, end, source_age="any")
+ return get_rows_synced_by_team(begin, end)
@timed_log()
@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
def get_teams_with_free_historical_rows_synced_in_period(begin: datetime, end: datetime) -> list:
- if begin >= dwh_pricing_free_period_start and begin < dwh_pricing_free_period_end:
- # during the free period, all rows get reported as free historical rows synced
- return _rows_synced_totals(begin, end, source_age="any")
-
- return _rows_synced_totals(begin, end, source_age="new_only")
+ return get_free_historical_rows_synced_by_team(begin, end)
@timed_log()
diff --git a/posthog/usage_ingestion/__init__.py b/posthog/usage_ingestion/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/usage_ingestion/client.py b/posthog/usage_ingestion/client.py
new file mode 100644
index 000000000000..37a3e023d775
--- /dev/null
+++ b/posthog/usage_ingestion/client.py
@@ -0,0 +1,98 @@
+import os
+from collections.abc import Iterable
+from dataclasses import field
+from time import time
+
+import grpc
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.usage_ingestion.generated.usage_ingestion.v1 import service_pb2, service_pb2_grpc
+
+logger = structlog.get_logger(__name__)
+
+
+@frozen
+class UsageRecord:
+ record_id: str
+ producer_id: str
+ team_id: int
+ usage_key: str
+ unit: str
+ quantity: int
+ # Emit time from our own clock. toDate of it is part of the storage sorting key, so a
+ # value taken from customer data would decide whether these records deduplicate.
+ timestamp_ms: int = field(default_factory=lambda: int(time() * 1000))
+
+
+def team_is_enabled(team_id: int) -> bool:
+ raw = os.environ.get("USAGE_INGESTION_REPORT_TEAMS", "").strip()
+ return raw == "*" or str(team_id) in {value.strip() for value in raw.split(",") if value.strip()}
+
+
+def _timeout_seconds() -> float:
+ # The env var is milliseconds everywhere else, but grpc takes seconds.
+ return float(os.environ.get("USAGE_INGESTION_TIMEOUT_MS", "5000")) / 1000
+
+
+def _to_send(records: Iterable[UsageRecord]) -> tuple[list[UsageRecord], str]:
+ return (
+ [record for record in records if team_is_enabled(record.team_id)],
+ os.environ.get("USAGE_INGESTION_ADDR", ""),
+ )
+
+
+def _request(records: list[UsageRecord]) -> service_pb2.IngestBillingUsageRequest:
+ return service_pb2.IngestBillingUsageRequest(
+ records=[
+ service_pb2.BillingUsageRecord(
+ record_id=record.record_id,
+ producer_id=record.producer_id,
+ team_id=record.team_id,
+ usage_key=record.usage_key,
+ unit=record.unit,
+ quantity=record.quantity,
+ timestamp_ms=record.timestamp_ms,
+ )
+ for record in records
+ ]
+ )
+
+
+# Every producer calls these after committing work of its own, and the nightly report is still
+# the billing source of truth, so a record is worth less than the caller it runs in. Nothing
+# escapes either function — not a bad address, not an unencodable field, not an RPC error.
+# Building the request sits inside the try for that reason.
+
+
+def report_usage(records: Iterable[UsageRecord], *, site: str) -> None:
+ enabled, address = _to_send(records)
+ if not enabled or not address:
+ return
+
+ try:
+ with grpc.insecure_channel(address) as channel:
+ service_pb2_grpc.UsageIngestionStub(channel).IngestBillingUsage(
+ _request(enabled), timeout=_timeout_seconds()
+ )
+ except Exception:
+ logger.warning("usage_ingestion_report_failed", site=site, records=len(enabled), exc_info=True)
+
+
+async def areport_usage(records: Iterable[UsageRecord], *, site: str) -> None:
+ """Async variant, for producers already on an event loop.
+
+ Prefer this to `asyncio.to_thread(report_usage, ...)`: that borrows a worker from the default
+ executor, which a hot loop of `to_thread` calls has exhausted before.
+ """
+ enabled, address = _to_send(records)
+ if not enabled or not address:
+ return
+
+ try:
+ async with grpc.aio.insecure_channel(address) as channel:
+ await service_pb2_grpc.UsageIngestionStub(channel).IngestBillingUsage(
+ _request(enabled), timeout=_timeout_seconds()
+ )
+ except Exception:
+ logger.warning("usage_ingestion_report_failed", site=site, records=len(enabled), exc_info=True)
diff --git a/posthog/usage_ingestion/generated/__init__.py b/posthog/usage_ingestion/generated/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/usage_ingestion/generated/usage_ingestion/__init__.py b/posthog/usage_ingestion/generated/usage_ingestion/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/posthog/usage_ingestion/generated/usage_ingestion/__init__.py
@@ -0,0 +1 @@
+
diff --git a/posthog/usage_ingestion/generated/usage_ingestion/v1/__init__.py b/posthog/usage_ingestion/generated/usage_ingestion/v1/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/posthog/usage_ingestion/generated/usage_ingestion/v1/__init__.py
@@ -0,0 +1 @@
+
diff --git a/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2.py b/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2.py
new file mode 100644
index 000000000000..43a1db8ffbeb
--- /dev/null
+++ b/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2.py
@@ -0,0 +1,40 @@
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: usage_ingestion/v1/service.proto
+# Protobuf Python Version: 5.29.0
+"""Generated protocol buffer code."""
+
+from google.protobuf import (
+ descriptor as _descriptor,
+ descriptor_pool as _descriptor_pool,
+ runtime_version as _runtime_version,
+ symbol_database as _symbol_database,
+)
+from google.protobuf.internal import builder as _builder
+
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC, 5, 29, 0, "", "usage_ingestion/v1/service.proto"
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b'\n usage_ingestion/v1/service.proto\x12\x12usage_ingestion.v1"\x96\x01\n\x12\x42illingUsageRecord\x12\x0f\n\x07team_id\x18\x01 \x01(\x03\x12\x14\n\x0ctimestamp_ms\x18\x02 \x01(\x03\x12\x13\n\x0bproducer_id\x18\x03 \x01(\t\x12\x11\n\tusage_key\x18\x04 \x01(\t\x12\x11\n\trecord_id\x18\x05 \x01(\t\x12\x10\n\x08quantity\x18\x06 \x01(\x03\x12\x0c\n\x04unit\x18\x07 \x01(\t"T\n\x19IngestBillingUsageRequest\x12\x37\n\x07records\x18\x01 \x03(\x0b\x32&.usage_ingestion.v1.BillingUsageRecord"9\n\x1aIngestBillingUsageResponse\x12\x1b\n\x13\x61\x63\x63\x65pted_record_ids\x18\x01 \x03(\t2\x85\x01\n\x0eUsageIngestion\x12s\n\x12IngestBillingUsage\x12-.usage_ingestion.v1.IngestBillingUsageRequest\x1a..usage_ingestion.v1.IngestBillingUsageResponseb\x06proto3'
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "usage_ingestion.v1.service_pb2", _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ DESCRIPTOR._loaded_options = None
+ _globals["_BILLINGUSAGERECORD"]._serialized_start = 57
+ _globals["_BILLINGUSAGERECORD"]._serialized_end = 207
+ _globals["_INGESTBILLINGUSAGEREQUEST"]._serialized_start = 209
+ _globals["_INGESTBILLINGUSAGEREQUEST"]._serialized_end = 293
+ _globals["_INGESTBILLINGUSAGERESPONSE"]._serialized_start = 295
+ _globals["_INGESTBILLINGUSAGERESPONSE"]._serialized_end = 352
+ _globals["_USAGEINGESTION"]._serialized_start = 355
+ _globals["_USAGEINGESTION"]._serialized_end = 488
+# @@protoc_insertion_point(module_scope)
diff --git a/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2.pyi b/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2.pyi
new file mode 100644
index 000000000000..076f9cfb08fd
--- /dev/null
+++ b/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2.pyi
@@ -0,0 +1,56 @@
+from collections.abc import (
+ Iterable as _Iterable,
+ Mapping as _Mapping,
+)
+from typing import (
+ ClassVar as _ClassVar,
+ Optional as _Optional,
+ Union as _Union,
+)
+
+from google.protobuf import (
+ descriptor as _descriptor,
+ message as _message,
+)
+from google.protobuf.internal import containers as _containers
+
+DESCRIPTOR: _descriptor.FileDescriptor
+
+class BillingUsageRecord(_message.Message):
+ __slots__ = ("team_id", "timestamp_ms", "producer_id", "usage_key", "record_id", "quantity", "unit")
+ TEAM_ID_FIELD_NUMBER: _ClassVar[int]
+ TIMESTAMP_MS_FIELD_NUMBER: _ClassVar[int]
+ PRODUCER_ID_FIELD_NUMBER: _ClassVar[int]
+ USAGE_KEY_FIELD_NUMBER: _ClassVar[int]
+ RECORD_ID_FIELD_NUMBER: _ClassVar[int]
+ QUANTITY_FIELD_NUMBER: _ClassVar[int]
+ UNIT_FIELD_NUMBER: _ClassVar[int]
+ team_id: int
+ timestamp_ms: int
+ producer_id: str
+ usage_key: str
+ record_id: str
+ quantity: int
+ unit: str
+ def __init__(
+ self,
+ team_id: _Optional[int] = ...,
+ timestamp_ms: _Optional[int] = ...,
+ producer_id: _Optional[str] = ...,
+ usage_key: _Optional[str] = ...,
+ record_id: _Optional[str] = ...,
+ quantity: _Optional[int] = ...,
+ unit: _Optional[str] = ...,
+ ) -> None: ...
+
+class IngestBillingUsageRequest(_message.Message):
+ __slots__ = ("records",)
+ RECORDS_FIELD_NUMBER: _ClassVar[int]
+ records: _containers.RepeatedCompositeFieldContainer[BillingUsageRecord]
+ def __init__(self, records: _Optional[_Iterable[_Union[BillingUsageRecord, _Mapping]]] = ...) -> None: ...
+
+class IngestBillingUsageResponse(_message.Message):
+ __slots__ = ("accepted_record_ids",)
+ ACCEPTED_RECORD_IDS_FIELD_NUMBER: _ClassVar[int]
+ accepted_record_ids: _containers.RepeatedScalarFieldContainer[str]
+ def __init__(self, accepted_record_ids: _Optional[_Iterable[str]] = ...) -> None: ...
diff --git a/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2_grpc.py b/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2_grpc.py
new file mode 100644
index 000000000000..991b2da0707a
--- /dev/null
+++ b/posthog/usage_ingestion/generated/usage_ingestion/v1/service_pb2_grpc.py
@@ -0,0 +1,119 @@
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+"""Client and server classes corresponding to protobuf-defined services."""
+
+import grpc
+
+from . import service_pb2 as usage__ingestion_dot_v1_dot_service__pb2
+
+GRPC_GENERATED_VERSION = "1.71.2"
+GRPC_VERSION = grpc.__version__
+_version_not_supported = False
+
+try:
+ from grpc._utilities import first_version_is_lower
+
+ _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
+except ImportError:
+ _version_not_supported = True
+
+if _version_not_supported:
+ raise RuntimeError(
+ f"The grpc package installed is at version {GRPC_VERSION},"
+ + f" but the generated code in usage_ingestion/v1/service_pb2_grpc.py depends on"
+ + f" grpcio>={GRPC_GENERATED_VERSION}."
+ + f" Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}"
+ + f" or downgrade your generated code using grpcio-tools<={GRPC_VERSION}."
+ )
+
+
+class UsageIngestionStub:
+ """UsageIngestion accepts usage records for durable analytics. Producers must reuse
+ record_id when retrying a record. The service preserves producer-supplied event
+ time and assigns insertion time when it publishes.
+
+ IngestBillingUsage carries tenant-billable usage: exact, idempotent, retained
+ indefinitely. Cost and resource metering is a separate RPC and table.
+ """
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.IngestBillingUsage = channel.unary_unary(
+ "/usage_ingestion.v1.UsageIngestion/IngestBillingUsage",
+ request_serializer=usage__ingestion_dot_v1_dot_service__pb2.IngestBillingUsageRequest.SerializeToString,
+ response_deserializer=usage__ingestion_dot_v1_dot_service__pb2.IngestBillingUsageResponse.FromString,
+ _registered_method=True,
+ )
+
+
+class UsageIngestionServicer:
+ """UsageIngestion accepts usage records for durable analytics. Producers must reuse
+ record_id when retrying a record. The service preserves producer-supplied event
+ time and assigns insertion time when it publishes.
+
+ IngestBillingUsage carries tenant-billable usage: exact, idempotent, retained
+ indefinitely. Cost and resource metering is a separate RPC and table.
+ """
+
+ def IngestBillingUsage(self, request, context):
+ """Missing associated documentation comment in .proto file."""
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details("Method not implemented!")
+ raise NotImplementedError("Method not implemented!")
+
+
+def add_UsageIngestionServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ "IngestBillingUsage": grpc.unary_unary_rpc_method_handler(
+ servicer.IngestBillingUsage,
+ request_deserializer=usage__ingestion_dot_v1_dot_service__pb2.IngestBillingUsageRequest.FromString,
+ response_serializer=usage__ingestion_dot_v1_dot_service__pb2.IngestBillingUsageResponse.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler("usage_ingestion.v1.UsageIngestion", rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+ server.add_registered_method_handlers("usage_ingestion.v1.UsageIngestion", rpc_method_handlers)
+
+
+# This class is part of an EXPERIMENTAL API.
+class UsageIngestion:
+ """UsageIngestion accepts usage records for durable analytics. Producers must reuse
+ record_id when retrying a record. The service preserves producer-supplied event
+ time and assigns insertion time when it publishes.
+
+ IngestBillingUsage carries tenant-billable usage: exact, idempotent, retained
+ indefinitely. Cost and resource metering is a separate RPC and table.
+ """
+
+ @staticmethod
+ def IngestBillingUsage(
+ request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None,
+ ):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ "/usage_ingestion.v1.UsageIngestion/IngestBillingUsage",
+ usage__ingestion_dot_v1_dot_service__pb2.IngestBillingUsageRequest.SerializeToString,
+ usage__ingestion_dot_v1_dot_service__pb2.IngestBillingUsageResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True,
+ )
diff --git a/posthog/usage_ingestion/test_client.py b/posthog/usage_ingestion/test_client.py
new file mode 100644
index 000000000000..b44bb0b717a8
--- /dev/null
+++ b/posthog/usage_ingestion/test_client.py
@@ -0,0 +1,48 @@
+import pytest
+from unittest.mock import patch
+
+import grpc
+
+from posthog.usage_ingestion.client import UsageRecord, _timeout_seconds, areport_usage, report_usage, team_is_enabled
+
+ERRORS = [grpc.RpcError(), RuntimeError("boom")]
+REPORTING_ENV = {"USAGE_INGESTION_ADDR": "localhost:1", "USAGE_INGESTION_REPORT_TEAMS": "*"}
+RECORD = UsageRecord(record_id="r", producer_id="p", team_id=2, usage_key="k", unit="rows", quantity=1)
+
+
+def test_team_is_enabled_uses_the_shared_team_list(monkeypatch) -> None:
+ monkeypatch.setenv("USAGE_INGESTION_REPORT_TEAMS", "2, 4")
+
+ assert team_is_enabled(2)
+ assert team_is_enabled(4)
+ assert not team_is_enabled(3)
+
+
+def test_team_is_enabled_supports_all_teams(monkeypatch) -> None:
+ monkeypatch.setenv("USAGE_INGESTION_REPORT_TEAMS", "*")
+
+ assert team_is_enabled(123)
+
+
+def test_timeout_converts_milliseconds_to_the_seconds_grpc_expects(monkeypatch) -> None:
+ monkeypatch.delenv("USAGE_INGESTION_TIMEOUT_MS", raising=False)
+ assert _timeout_seconds() == 5.0
+
+ monkeypatch.setenv("USAGE_INGESTION_TIMEOUT_MS", "250")
+ assert _timeout_seconds() == 0.25
+
+
+# Every producer calls these after committing work of its own, so a raise here fails an activity
+# that is already done, and the retry re-runs everything that ran before it.
[email protected]("error", ERRORS)
+def test_reporting_never_raises_into_the_producer(error: Exception) -> None:
+ with patch.dict("os.environ", REPORTING_ENV):
+ with patch("posthog.usage_ingestion.client.grpc.insecure_channel", side_effect=error):
+ report_usage([RECORD], site="test")
+
+
[email protected]("error", ERRORS)
+async def test_async_reporting_never_raises_into_the_producer(error: Exception) -> None:
+ with patch.dict("os.environ", REPORTING_ENV):
+ with patch("posthog.usage_ingestion.client.grpc.aio.insecure_channel", side_effect=error):
+ await areport_usage([RECORD], site="test")
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index 0d65e4874c16..1743603a78bf 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -1058,7 +1058,12 @@ def update_batch_export_run(
run_id: The id of the BatchExportRun to update.
"""
# nosemgrep: idor-lookup-without-team (internal service, team_id passed as parameter)
- model = BatchExportRun.objects.select_related("batch_export", "batch_export__destination").filter(id=run_id)
+ model = BatchExportRun.objects.select_related(
+ "batch_export",
+ "batch_export__destination",
+ "batch_export_on_demand",
+ "batch_export_on_demand__destination",
+ ).filter(id=run_id)
update_at = dt.datetime.now(dt.UTC)
updated = model.update(
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index e91938bb5f37..27bbe9feeecb 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -24,8 +24,9 @@ from posthog.tasks.email import get_members_to_notify_for_pipeline_error, send_b
from posthog.temporal.common.clickhouse import ClickHouseClient
from posthog.temporal.common.client import connect
from posthog.temporal.common.logger import get_logger, get_write_only_logger
+from posthog.usage_ingestion.client import UsageRecord, areport_usage
-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRun
+from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
from products.batch_exports.backend.service import (
BackfillDetails,
BatchExportField,
@@ -568,6 +569,18 @@ class FinishBatchExportRunInputs:
on_demand: bool = False
+def _is_billable(run: BatchExportRun) -> bool:
+ # Mirrors get_teams_with_rows_exported_in_period in the nightly report, which bills neither
+ # HTTP nor Workflows destinations, and skips a run whose export has been deleted.
+ export = run.batch_export or run.batch_export_on_demand
+ if export is None or export.deleted:
+ return False
+ return export.destination.type not in (
+ BatchExportDestination.Destination.HTTP,
+ BatchExportDestination.Destination.WORKFLOWS,
+ )
+
+
@activity.defn
async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:
"""Activity that finishes a 'BatchExportRun'.
@@ -615,6 +628,30 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:
**update_params,
)
+ # The run is already written, so nothing here may fail the activity — not the destination
+ # lookup `_is_billable` walks, not the report itself.
+ try:
+ if (
+ batch_export_run.status == BatchExportRun.Status.COMPLETED
+ and batch_export_run.records_completed
+ and _is_billable(batch_export_run)
+ ):
+ await areport_usage(
+ [
+ UsageRecord(
+ record_id=str(batch_export_run.id),
+ producer_id="batch-exports",
+ team_id=inputs.team_id,
+ usage_key="batch_export_rows",
+ unit="rows",
+ quantity=batch_export_run.records_completed,
+ )
+ ],
+ site="batch_exports",
+ )
+ except Exception:
+ LOGGER.exception("batch_export_run.usage_collection_failed", batch_export_run_id=inputs.id)
+
if batch_export_run.status == BatchExportRun.Status.FAILED_RETRYABLE:
# We should never get here as we do not have a retry limit.
# So, users should never be asked to retry for things we can retry ourselves.
diff --git a/products/batch_exports/backend/tests/temporal/test_run_updates.py b/products/batch_exports/backend/tests/temporal/test_run_updates.py
index d4bdada5fa25..4e5927f2d95f 100644
--- a/products/batch_exports/backend/tests/temporal/test_run_updates.py
+++ b/products/batch_exports/backend/tests/temporal/test_run_updates.py
@@ -11,12 +11,18 @@ from asgiref.sync import sync_to_async
from posthog.kafka_client.topics import KAFKA_APP_METRICS2, KAFKA_CDP_INTERNAL_EVENTS
from posthog.models import Organization, Team
-from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
+from products.batch_exports.backend.models.batch_export import (
+ BatchExport,
+ BatchExportDestination,
+ BatchExportOnDemand,
+ BatchExportRun,
+)
from products.batch_exports.backend.service import delete_batch_export, sync_batch_export
from products.batch_exports.backend.temporal.batch_exports import (
FinishBatchExportRunInputs,
OverBillingLimitError,
StartBatchExportRunInputs,
+ _is_billable,
finish_batch_export_run,
start_batch_export_run,
)
@@ -194,7 +200,8 @@ async def test_start_batch_export_run_does_not_check_billing_limit(activity_envi
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_finish_batch_export_run(activity_environment, team, batch_export):
[email protected]("usage_collection_raises", [False, True])
+async def test_finish_batch_export_run(activity_environment, team, batch_export, usage_collection_raises):
"""Test the export_run_status activity."""
start = dt.datetime(2023, 4, 24, tzinfo=dt.UTC)
end = dt.datetime(2023, 4, 25, tzinfo=dt.UTC)
@@ -219,7 +226,13 @@ async def test_finish_batch_export_run(activity_environment, team, batch_export)
status="Completed",
team_id=inputs.team_id,
)
- await activity_environment.run(finish_batch_export_run, finish_inputs)
+ # Usage is collected after the run is written, so a collector that raises must not cost the
+ # run its Completed status and send the whole export round again.
+ with unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports._is_billable",
+ side_effect=RuntimeError("boom") if usage_collection_raises else _is_billable,
+ ):
+ await activity_environment.run(finish_batch_export_run, finish_inputs)
runs = BatchExportRun.objects.filter(id=run_id)
run = await sync_to_async(runs.first)()
@@ -588,3 +601,24 @@ async def test_start_batch_export_run_produces_failed_billing_internal_event(act
}
assert len(get_produced_app_metrics_payloads(mocked_try_produce)) == 1
+
+
[email protected]("on_demand", [False, True])
+ "destination_type,deleted,billable",
+ [
+ (BatchExportDestination.Destination.S3, False, True),
+ (BatchExportDestination.Destination.HTTP, False, False),
+ (BatchExportDestination.Destination.WORKFLOWS, False, False),
+ (BatchExportDestination.Destination.S3, True, False),
+ ],
+)
+def test_usage_is_reported_only_for_what_the_nightly_report_bills(destination_type, deleted, billable, on_demand):
+ destination = BatchExportDestination(type=destination_type)
+ run = BatchExportRun()
+ if on_demand:
+ run.batch_export_on_demand = BatchExportOnDemand(destination=destination, deleted=deleted)
+ else:
+ run.batch_export = BatchExport(destination=destination, deleted=deleted)
+
+ assert _is_billable(run) is billable
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 289ce0af8219..452937ec1ae9 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -743,7 +743,6 @@ warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.manage
warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder construct 1
warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1
warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(create) 1
-warehouse_sources.ExternalDataJob posthog.tasks.usage_report instance-many(annotate) 1
warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.data_load.source_templates instance-single 2
warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.jobs lock 1
warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.notifications instance-many(filter) 2
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.py
index 2dd747fc15ef..6d5ce262a2da 100644
--- a/products/replay_vision/backend/temporal/activities/observation_state.py
+++ b/products/replay_vision/backend/temporal/activities/observation_state.py
@@ -9,6 +9,7 @@ import posthoganalytics
from temporalio import activity
from posthog.settings import SITE_URL
+from posthog.usage_ingestion.client import UsageRecord, report_usage
from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
@@ -266,3 +267,19 @@ def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs)
"project": str(obs["team__uuid"]),
},
)
+ # Last, and off the receipt rather than the receipt being new: the transition above already
+ # committed the credits, and `record_id` deduplicates a resend, so a retry that gets this far
+ # again costs nothing. Everything that has to happen for a scan happens before this line.
+ report_usage(
+ [
+ UsageRecord(
+ record_id=str(inputs.observation_id),
+ producer_id="replay-vision",
+ team_id=obs["team_id"],
+ usage_key="replay_vision_credits",
+ unit="credits",
+ quantity=credits,
+ )
+ ],
+ site="replay_vision",
+ )
diff --git a/products/warehouse_sources/backend/billing.py b/products/warehouse_sources/backend/billing.py
new file mode 100644
index 000000000000..c3b70abdf3fc
--- /dev/null
+++ b/products/warehouse_sources/backend/billing.py
@@ -0,0 +1,87 @@
+"""Bills warehouse rows synced.
+
+Two meters split the same set of completed jobs. `rows_synced` is what a customer pays
+for; `free_historical_rows_synced` is the rest, currently a source's first week of
+syncing. The nightly report aggregates them over a period, the quota meter in
+`row_tracking` counts the billable half against the billing cycle, and the realtime
+collector classifies one job as it finishes.
+
+All three read the rules from here, and `tests/test_billing.py` runs the period queries
+and the per-job classifier over the same jobs to check they still agree.
+"""
+
+from datetime import UTC, datetime, timedelta
+
+from django.db.models import F, Q, QuerySet, Sum
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob, billable_destination_multiplier
+from products.warehouse_sources.backend.types import ExternalDataJobStatus
+
+ROWS_SYNCED_USAGE_KEY = "warehouse_rows_synced"
+FREE_HISTORICAL_ROWS_SYNCED_USAGE_KEY = "warehouse_free_historical_rows_synced"
+
+# A source's first week of syncing is free, so its jobs bill on the free historical meter.
+FREE_HISTORICAL_WINDOW = timedelta(days=7)
+
+# Everything synced in this window was free, whatever the source's age.
+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 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.
+
+ Reads `job.pipeline`, so select it in. The guards mirror the filters the period
+ queries below apply: a job bills only when it completed, stayed billable, and moved
+ rows.
+ """
+ if (
+ job.status != ExternalDataJobStatus.COMPLETED
+ or not job.billable
+ or not job.rows_synced
+ or job.finished_at is None
+ ):
+ return None
+ return _usage_key(job.finished_at, job.pipeline.created_at), job.rows_synced * max(1, len(job.destination_ids))
+
+
+def _usage_key(finished_at: datetime, source_created_at: datetime) -> str:
+ # The period queries measure a source's age against the period end; this measures it
+ # against the job's own finish, the same way the quota meter in `row_tracking` does.
+ # The two disagree only for a source created in the up-to-24h band around the seven-day
+ # mark, which the report resolves in the customer's favour.
+ if FREE_PERIOD_START <= finished_at < FREE_PERIOD_END:
+ return FREE_HISTORICAL_ROWS_SYNCED_USAGE_KEY
+ if source_created_at >= finished_at - FREE_HISTORICAL_WINDOW:
+ return FREE_HISTORICAL_ROWS_SYNCED_USAGE_KEY
+ return ROWS_SYNCED_USAGE_KEY
+
+
+def _completed_billable_jobs(begin: datetime, end: datetime) -> QuerySet[ExternalDataJob]:
+ return ExternalDataJob.objects.filter(
+ finished_at__gte=begin,
+ finished_at__lte=end,
+ billable=True,
+ status=ExternalDataJobStatus.COMPLETED,
+ )
+
+
+def _by_team(jobs: QuerySet[ExternalDataJob]) -> list:
+ return list(jobs.values("team_id").annotate(total=Sum(F("rows_synced") * billable_destination_multiplier())))
+
+
+def get_rows_synced_by_team(begin: datetime, end: datetime) -> list:
+ if FREE_PERIOD_START <= begin < FREE_PERIOD_END:
+ return []
+
+ jobs = _completed_billable_jobs(begin, end)
+ if begin >= FREE_PERIOD_END:
+ jobs = jobs.filter(~Q(pipeline__created_at__gte=end - FREE_HISTORICAL_WINDOW))
+ return _by_team(jobs)
+
+
+def get_free_historical_rows_synced_by_team(begin: datetime, end: datetime) -> list:
+ jobs = _completed_billable_jobs(begin, end)
+ if not (FREE_PERIOD_START <= begin < FREE_PERIOD_END):
+ jobs = jobs.filter(pipeline__created_at__gte=end - FREE_HISTORICAL_WINDOW)
+ return _by_team(jobs)
diff --git a/products/warehouse_sources/backend/facade/billing.py b/products/warehouse_sources/backend/facade/billing.py
new file mode 100644
index 000000000000..c9f25c30c8ca
--- /dev/null
+++ b/products/warehouse_sources/backend/facade/billing.py
@@ -0,0 +1,12 @@
+"""Billing-facing exports for warehouse_sources.
+
+The usage reporter (posthog/tasks/usage_report.py) lives in the ``posthog`` module,
+which may only import ``products.warehouse_sources`` through the facade (see tach.toml).
+"""
+
+from products.warehouse_sources.backend.billing import get_free_historical_rows_synced_by_team, get_rows_synced_by_team
+
+__all__ = [
+ "get_free_historical_rows_synced_by_team",
+ "get_rows_synced_by_team",
+]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index b8ff97dff2f7..bd91881e32fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -25,6 +25,7 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.schedule import trigger_schedule_buffer_one
from posthog.temporal.common.utils import APP_DB_ERROR_PREFIX, READ_ONLY_TRANSACTION_PHRASE
from posthog.temporal.utils import CDPProducerWorkflowInputs, ExternalDataWorkflowInputs
+from posthog.usage_ingestion.client import UsageRecord, areport_usage
from posthog.utils import get_machine_id
from products.data_warehouse.backend.facade.api import (
@@ -39,6 +40,7 @@ from products.managed_warehouse.backend.facade.temporal import (
DuckLakeRegisterDataImportsWorkflow,
build_register_data_imports_workflow_id,
)
+from products.warehouse_sources.backend.billing import billed_usage_for_job
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
AUTO_DISABLED_JOB_ERROR,
@@ -493,6 +495,35 @@ async def update_external_data_job_model(inputs: UpdateExternalDataJobStatusInpu
},
)
+ if inputs.status == ExternalDataJob.Status.COMPLETED:
+ # The status write above already committed, so nothing here may fail the finalization —
+ # not the read back, not the classification. A job we cannot bill for is worth less than
+ # a sync that has to run again.
+ try:
+ # Read the job back rather than trusting `inputs`: the status write is absorbing, so
+ # it can leave a job that stayed FAILED, and the row counter is written elsewhere.
+ completed_job = await database_sync_to_async_pool(
+ ExternalDataJob.objects.select_related("pipeline").filter(team_id=inputs.team_id, id=job_id).first
+ )()
+ billed = billed_usage_for_job(completed_job) if completed_job else None
+ if completed_job and billed:
+ usage_key, rows = billed
+ await areport_usage(
+ [
+ UsageRecord(
+ record_id=str(completed_job.id),
+ producer_id="warehouse-sources",
+ team_id=completed_job.team_id,
+ usage_key=usage_key,
+ unit="rows",
+ quantity=rows,
+ )
+ ],
+ site="warehouse_rows",
+ )
+ except Exception:
+ logger.exception(f"Could not collect usage for external data job {job_id}")
+
logger.info(
f"Updated external data job with for external data source {job_id} to status {inputs.status}",
)
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 758e0f92b1cd..1f2116f7b110 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/row_tracking.py
@@ -1,7 +1,7 @@
import uuid
import asyncio
from contextlib import asynccontextmanager
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, datetime
from typing import TYPE_CHECKING
from django.conf import settings
@@ -25,6 +25,7 @@ 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.models.external_data_job import ExternalDataJob, billable_destination_multiplier
if TYPE_CHECKING:
@@ -157,10 +158,6 @@ async def get_all_rows_for_team(team_id: int) -> int:
return 0
-# To be removed after 2025-11-06
-dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)
-dwh_pricing_free_period_end = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)
-
# The billing-period sum only moves when a job completes, so serving it from a cache for a
# few minutes costs at most the rows one organization completes inside the window. The hard
# stop behind this check (check_billing_limits_activity, reading the quota-limiting cache)
@@ -216,7 +213,7 @@ def _rows_synced_in_billing_period(
# Rows bill once per destination the run delivered to. A run completes only when every
# destination took it, so the count is exact.
result = ExternalDataJob.objects.filter(
- Q(finished_at__gte=F("pipeline__created_at") + timedelta(days=7)),
+ Q(finished_at__gte=F("pipeline__created_at") + FREE_HISTORICAL_WINDOW),
team_id__in=team_ids,
finished_at__gte=billing_cycle_start,
billable=True,
@@ -243,20 +240,16 @@ 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) - timedelta(days=7):
+ if source.created_at >= datetime.now(UTC) - FREE_HISTORICAL_WINDOW:
await logger.ainfo(
f"Skipping billing limits check for newly created data source for 7-days free rows. source.created_at = {source.created_at}"
)
return False
# Handle free period for data synced during free period (to be removed after 2025-11-06)
- if (
- not TEST
- and datetime.now(UTC) >= dwh_pricing_free_period_start
- and datetime.now(UTC) <= dwh_pricing_free_period_end
- ):
+ if not TEST and datetime.now(UTC) >= FREE_PERIOD_START and datetime.now(UTC) <= FREE_PERIOD_END:
await logger.ainfo(
- f"Skipping billing limits check for data synced during free period from {dwh_pricing_free_period_start} to {dwh_pricing_free_period_end}."
+ f"Skipping billing limits check for data synced during free period from {FREE_PERIOD_START} to {FREE_PERIOD_END}."
)
return False
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 2e8cb60c7507..4a843a9d49a0 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
@@ -21,8 +21,8 @@ from structlog.types import FilteringBoundLogger
from posthog.models import Team
from posthog.redis import get_client
from posthog.sync import database_sync_to_async
-from posthog.tasks.usage_report import ExternalDataJob
+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,
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 c379a1656d9b..fca2a37730a7 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
@@ -1,6 +1,6 @@
import typing
import dataclasses
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, datetime
from django.db import close_old_connections
@@ -11,6 +11,8 @@ 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 ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited
LOGGER = get_logger(__name__)
@@ -29,11 +31,6 @@ class CheckBillingLimitsActivityInputs:
}
-# To be removed after 2025-11-06
-dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)
-dwh_pricing_free_period_end = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)
-
-
@activity.defn
def check_billing_limits_activity(inputs: CheckBillingLimitsActivityInputs) -> bool:
from products.warehouse_sources.backend.temporal.data_imports.external_data_job import (
@@ -61,19 +58,15 @@ def check_billing_limits_activity(inputs: CheckBillingLimitsActivityInputs) -> b
logger.info("Skipping billing limits check for non-billable job")
return False
- if source.created_at >= datetime.now(UTC) - timedelta(days=7):
+ if source.created_at >= datetime.now(UTC) - FREE_HISTORICAL_WINDOW:
logger.info(
f"Skipping billing limits check for newly created data source for 7-days free rows. source.created_at = {source.created_at}"
)
return False
- if (
- not TEST
- and datetime.now(UTC) >= dwh_pricing_free_period_start
- and datetime.now(UTC) <= dwh_pricing_free_period_end
- ):
+ if not TEST and datetime.now(UTC) >= FREE_PERIOD_START and datetime.now(UTC) <= FREE_PERIOD_END:
logger.info(
- f"Skipping billing limits check for data synced during free period from {dwh_pricing_free_period_start} to {dwh_pricing_free_period_end}."
+ f"Skipping billing limits check for data synced during free period from {FREE_PERIOD_START} to {FREE_PERIOD_END}."
)
return False
diff --git a/products/warehouse_sources/backend/tests/test_billing.py b/products/warehouse_sources/backend/tests/test_billing.py
new file mode 100644
index 000000000000..305c63c67811
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_billing.py
@@ -0,0 +1,111 @@
+import uuid
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest
+
+from posthog.models.team import Team
+
+from products.warehouse_sources.backend.billing import (
+ FREE_HISTORICAL_ROWS_SYNCED_USAGE_KEY,
+ FREE_PERIOD_START,
+ ROWS_SYNCED_USAGE_KEY,
+ billed_usage_for_job,
+ get_free_historical_rows_synced_by_team,
+ get_rows_synced_by_team,
+)
+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.types import ExternalDataJobStatus
+
+PERIOD_BEGIN = datetime(2026, 3, 10, 0, 0, 0, tzinfo=UTC)
+PERIOD_END = datetime(2026, 3, 10, 23, 59, 59, tzinfo=UTC)
+FINISHED_AT = datetime(2026, 3, 10, 12, 0, 0, tzinfo=UTC)
+
+
+class TestWarehouseRowsBilling(BaseTest):
+ def _job(
+ self,
+ *,
+ source_created_at: datetime,
+ rows: int = 100,
+ finished_at: datetime | None = FINISHED_AT,
+ status: str = ExternalDataJobStatus.COMPLETED,
+ billable: bool = True,
+ team_id: int | None = None,
+ destination_ids: list[str] | None = None,
+ ) -> ExternalDataJob:
+ source = ExternalDataSource.objects.create(
+ team_id=team_id or self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ # created_at is auto_now_add, so it can only be set after the insert.
+ ExternalDataSource.objects.filter(id=source.id).update(created_at=source_created_at)
+ source.refresh_from_db()
+ return ExternalDataJob.objects.create(
+ team_id=team_id or self.team.pk,
+ pipeline=source,
+ status=status,
+ rows_synced=rows,
+ billable=billable,
+ finished_at=finished_at,
+ destination_ids=destination_ids or [],
+ )
+
+ def _report_totals(self, begin: datetime = PERIOD_BEGIN, end: datetime = PERIOD_END) -> dict[tuple[int, str], int]:
+ return {
+ (row["team_id"], usage_key): row["total"]
+ for usage_key, rows in (
+ (ROWS_SYNCED_USAGE_KEY, get_rows_synced_by_team(begin, end)),
+ (FREE_HISTORICAL_ROWS_SYNCED_USAGE_KEY, get_free_historical_rows_synced_by_team(begin, end)),
+ )
+ for row in rows
+ }
+
+ def _collector_totals(self) -> dict[tuple[int, str], int]:
+ totals: dict[tuple[int, str], int] = {}
+ for job in ExternalDataJob.objects.select_related("pipeline").all():
+ billed = billed_usage_for_job(job)
+ if billed is None:
+ continue
+ usage_key, rows = billed
+ totals[(job.team_id, usage_key)] = totals.get((job.team_id, usage_key), 0) + rows
+ return totals
+
+ def test_collector_and_report_bill_the_same_jobs(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ self._job(source_created_at=PERIOD_END - timedelta(days=30), rows=100, destination_ids=["one", "two"])
+ self._job(source_created_at=PERIOD_END - timedelta(days=8), rows=200)
+ self._job(source_created_at=PERIOD_END - timedelta(days=2), rows=400)
+ self._job(source_created_at=PERIOD_END - timedelta(days=30), rows=800, team_id=other_team.pk)
+ # Bill nothing: the report's filters drop each of these.
+ self._job(source_created_at=PERIOD_END - timedelta(days=30), rows=1, billable=False)
+ self._job(source_created_at=PERIOD_END - timedelta(days=30), rows=2, status=ExternalDataJobStatus.FAILED)
+ self._job(source_created_at=PERIOD_END - timedelta(days=30), rows=4, finished_at=None)
+ self._job(source_created_at=PERIOD_END - timedelta(days=30), rows=0)
+
+ expected = {
+ (self.team.pk, ROWS_SYNCED_USAGE_KEY): 400,
+ (self.team.pk, FREE_HISTORICAL_ROWS_SYNCED_USAGE_KEY): 400,
+ (other_team.pk, ROWS_SYNCED_USAGE_KEY): 800,
+ }
+ assert self._report_totals() == expected
+ assert self._collector_totals() == expected
+
+ def test_collector_and_report_agree_during_the_free_period(self) -> None:
+ begin = FREE_PERIOD_START
+ end = FREE_PERIOD_START + timedelta(days=1)
+ self._job(source_created_at=begin - timedelta(days=30), rows=100, finished_at=begin + timedelta(hours=12))
+
+ expected = {(self.team.pk, FREE_HISTORICAL_ROWS_SYNCED_USAGE_KEY): 100}
+ assert self._report_totals(begin, end) == expected
+ assert self._collector_totals() == expected
+
+ def test_a_job_outside_the_period_bills_nothing_in_the_report(self) -> None:
+ self._job(
+ source_created_at=PERIOD_END - timedelta(days=30), rows=100, finished_at=PERIOD_END + timedelta(days=1)
+ )
+
+ assert self._report_totals() == {}