: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(billing): narrow sdk log scans for usage reports (#105117)
Pawel Cebula6c8cae0f8610
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 3f02860f1aa6..64f0fbb30943 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -72,6 +72,7 @@ from posthog.tasks.usage_report import (get_teams_with_billable_event_count_in_period,get_teams_with_posthog_code_credits_used_in_period,get_teams_with_query_metric,+ get_teams_with_sdk_logs_records_in_period,has_non_zero_usage,send_all_org_usage_reports,)@@ -3515,7 +3516,9 @@ class TestHogFunctionUsageReports(ClickhouseDestroyTablesMixin, TestCase, Clickhassert org_1_report[field] == value, fieldassert team_1_report[field] == value, field- def _logs_records_json(self, team_id: int, sdk_name: str | None, count: int) -> str:+ def _logs_records_json(+ self, team_id: int, sdk_name: str | None, count: int, timestamp: datetime | None = None+ ) -> str:resource_attributes = {"telemetry.sdk.name": sdk_name} if sdk_name is not None else {}lines = ""for _ in range(count):@@ -3524,7 +3527,7 @@ class TestHogFunctionUsageReports(ClickhouseDestroyTablesMixin, TestCase, Clickh{"uuid": str(uuid4()),"team_id": team_id,- "timestamp": now().strftime("%Y-%m-%d %H:%M:%S.%f"),+ "timestamp": (timestamp or now()).strftime("%Y-%m-%d %H:%M:%S.%f"),"observed_timestamp": now().strftime("%Y-%m-%d %H:%M:%S.%f"),"body": "test log line","severity_text": "info",@@ -3590,6 +3593,39 @@ class TestHogFunctionUsageReports(ClickhouseDestroyTablesMixin, TestCase, Clickhfield = f"{sdk}_logs_records_in_period"assert counters[field] == expected, f"{scope}: {field} should be {expected}, got {counters[field]}"+ @parameterized.expand([("aligned", 0, 0), ("partial_buckets", 3, 7)])+ def test_sdk_logs_counts_respect_period_and_team(self, _name: str, minute: int, second: int) -> None:+ self._setup_teams()+ sync_execute(f"TRUNCATE TABLE IF EXISTS {LOGS_LOCAL_TABLE}")+ begin = now().replace(hour=12, minute=minute, second=second, microsecond=0)+ end = begin + timedelta(minutes=10)+ team_id = self.org_1_team_1.id+ other_team_id = self.org_1_team_2.id++ lines = self._logs_records_json(team_id, "web", 5, begin - timedelta(seconds=1))+ lines += self._logs_records_json(team_id, "web", 3, begin)+ lines += self._logs_records_json(team_id, "web", 4, end - timedelta(seconds=1))+ lines += self._logs_records_json(team_id, "posthog-ios", 2, end - timedelta(seconds=1))+ lines += self._logs_records_json(team_id, "posthog-ios", 6, end)+ lines += self._logs_records_json(team_id, "posthog-node", 8, begin)+ lines += self._logs_records_json(team_id, None, 10, begin)+ lines += self._logs_records_json(other_team_id, "web", 9, begin)+ sync_execute(f"INSERT INTO logs_distributed FORMAT JSONEachRow\n{lines}")+ sync_execute(+ f"INSERT INTO logs_distributed FORMAT JSONEachRow\n{self._logs_records_json(team_id, 'web', 1, begin)}"+ )++ expected = {+ "web": [(team_id, 8)],+ "ios": [(team_id, 2)],+ "react_native": [],+ "android": [],+ "flutter": [],+ "ruby": [],+ }+ assert get_teams_with_sdk_logs_records_in_period(begin, end, [team_id]) == expected+ assert get_teams_with_sdk_logs_records_in_period(begin, end, []) == {sdk: [] for sdk in expected}+@parameterized.expand([# Per-signal MB is floored to whole decimal MB, and the billable combined metric isdiff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex a4c1cbbd6316..d88294e7fcf1 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -2634,9 +2634,10 @@ def get_teams_with_sdk_logs_records_in_period(tuples ready for `convert_team_usage_rows_to_dict`.`team_ids_with_logs` must be the team_ids that produced any log records in the same period- (typically the result of `get_teams_with_logs_records_in_period`). It's used as a primary-key- pre-filter on `logs_distributed` — without it, scanning the `resource_attributes` map cluster-wide- hits the Logs cluster's per-query scan-bytes ceiling. If the input is empty, the query is skipped.+ (typically the result of `get_teams_with_logs_records_in_period`). The resource index narrows the+ scan to matching resources before reading the `resource_attributes` map to reduce scanned bytes.+ Raw rows still determine the counts and exact time bounds.+ If the input is empty, the query is skipped.NB: query the physical `logs_distributed` table, not `logs`. `logs` is the HogQL table alias andonly resolves inside HogQL (`parse_select`); raw `sync_execute` runs ClickHouse SQL directly, where@@ -2653,6 +2654,17 @@ def get_teams_with_sdk_logs_records_in_period(resource_attributes['telemetry.sdk.name'] AS sdk_name,count() AS countFROM logs_distributed+ PREWHERE (team_id, resource_fingerprint) GLOBAL IN (+ SELECT team_id, resource_fingerprint+ FROM log_attributes_distributed+ WHERE team_id IN %(team_ids)s+ AND attribute_type = 'resource'+ AND attribute_key = 'telemetry.sdk.name'+ AND attribute_value IN %(sdk_names)s+ AND time_bucket >= toStartOfInterval(toDateTime(%(begin)s), INTERVAL 10 MINUTE)+ AND time_bucket <= toStartOfInterval(toDateTime(%(end)s), INTERVAL 10 MINUTE)+ GROUP BY team_id, resource_fingerprint+ )WHERE team_id IN %(team_ids)sAND timestamp >= %(begin)sAND timestamp < %(end)s