: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
chore(temporal): use itertools.batched instead of local copies (#90409)
Arno Hillend9407e7fe088
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.pyindex c1d87b336355..600cd0090632 100644--- a/posthog/temporal/ai_observability/eval_reports/activities.py+++ b/posthog/temporal/ai_observability/eval_reports/activities.py@@ -3,6 +3,7 @@import timeimport datetime as dtfrom collections import defaultdict+from itertools import batchedfrom typing import TYPE_CHECKING, NamedTuplefrom zoneinfo import ZoneInfo@@ -159,7 +160,9 @@ def _fetch_count_triggered_eval_report_candidate_groups() -> list[list[str]]:.values_list("id", "team_id")):ids_by_team[team_id].append(str(pk))- return [chunk for ids in ids_by_team.values() for chunk in _chunk(ids, COUNT_TRIGGER_QUERY_WIDTH)]+ return [+ list(chunk) for ids in ids_by_team.values() for chunk in batched(ids, COUNT_TRIGGER_QUERY_WIDTH, strict=False)+ ]def _load_count_triggered_report(report_id: str) -> "EvaluationReport | None":@@ -227,10 +230,6 @@ def _check_count_triggered_eval_report_sync(return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=count >= report.trigger_threshold)-def _chunk(items: list, size: int) -> list[list]:- return [items[index : index + size] for index in range(0, len(items), size)]--def _check_count_triggered_eval_reports_batch(report_ids: list[str],now: dt.datetime | None = None,@@ -287,7 +286,7 @@ def _check_count_triggered_eval_reports_batch(# have a comparable window — one stale report no longer sets the scan's lower# bound for every other report queued alongside it.entries.sort(key=lambda entry: entry[2])- for chunk in _chunk(entries, COUNT_TRIGGER_QUERY_WIDTH):+ for chunk in batched(entries, COUNT_TRIGGER_QUERY_WIDTH, strict=False):counts = _count_eval_results_for_reports_with_split_retry(team,[diff --git a/posthog/temporal/ai_observability/eval_reports/workflow.py b/posthog/temporal/ai_observability/eval_reports/workflow.pyindex 4dd5ef8a3715..c26c14f32fbe 100644--- a/posthog/temporal/ai_observability/eval_reports/workflow.py+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py@@ -3,6 +3,7 @@import jsonimport asynciofrom datetime import timedelta+from itertools import batchedfrom django.conf import settings@@ -162,7 +163,7 @@ async def _check_count_triggered_eval_report_candidates(report_ids: list[str]) -"not_deliverable": 0,}- for batch in _batch_report_ids(report_ids, COUNT_TRIGGER_CHECK_BATCH_SIZE):+ for batch in batched(report_ids, COUNT_TRIGGER_CHECK_BATCH_SIZE, strict=False):tasks = [temporalio.workflow.execute_activity(check_count_triggered_eval_report_activity,@@ -259,10 +260,6 @@ async def _check_count_triggered_eval_report_candidates_batched(report_id_groupsreturn due_report_ids-def _batch_report_ids(report_ids: list[str], batch_size: int) -> list[list[str]]:- return [report_ids[index : index + batch_size] for index in range(0, len(report_ids), batch_size)]--def _log_fan_out_failures(kind: str, report_ids: list[str], results: list) -> None:"""Log which child workflows failed in a fan-out, without re-raising."""failed: list[tuple[str, str]] = []diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.pyindex 78a68ae85934..8ce5174e8e3a 100644--- a/posthog/temporal/tests/usage_report/test_aggregator.py+++ b/posthog/temporal/tests/usage_report/test_aggregator.py@@ -1,7 +1,7 @@"""Pure-logic tests for the aggregator module.These cover the building blocks the aggregation activity composes:-`load_all_data`, `iter_chunk_lines`, `batched`, `build_manifest`,+`load_all_data`, `iter_chunk_lines`, `build_manifest`,`filter_org_reports`, `filter_orgs_with_usage`, `sort_org_reports`.No Django / Temporal / S3 required."""@@ -11,13 +11,11 @@ import dataclassesfrom datetime import UTC, datetimefrom typing import Any, cast-import pytestfrom unittest.mock import patchfrom posthog.tasks.usage_report import InstanceMetadata, OrgReport, UsageReportCountersfrom posthog.temporal.usage_report.aggregator import (add_pre_sandbox_compute_patch_defaults,- batched,build_manifest,filter_org_reports,filter_orgs_with_usage,@@ -39,26 +37,6 @@ def _ctx(run_id: str = "abc", report_completeness: ReportCompleteness = "partial)-# ---- batched ----------------------------------------------------------------def test_batched_yields_full_and_remainder() -> None:- assert list(batched([1, 2, 3, 4, 5], 2)) == [[1, 2], [3, 4], [5]]---def test_batched_empty_input() -> None:- assert list(batched([], 3)) == []---def test_batched_exact_multiple() -> None:- assert list(batched([1, 2, 3, 4], 2)) == [[1, 2], [3, 4]]---def test_batched_invalid_size_raises() -> None:- with pytest.raises(ValueError, match="positive"):- list(batched([1, 2], 0))--# ---- load_all_data -------------------------------------------------------diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.pyindex 6912565adfb6..a782c627398e 100644--- a/posthog/temporal/usage_report/activities.py+++ b/posthog/temporal/usage_report/activities.py@@ -9,6 +9,7 @@ elsewhere so these stay easy to read and mock in tests.import jsonimport timeimport asyncio+from itertools import batchedfrom typing import Anyfrom django.conf import settings@@ -23,7 +24,6 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.metrics import ExecutionTimeRecorderfrom posthog.temporal.usage_report.aggregator import (add_pre_sandbox_compute_patch_defaults,- batched,build_manifest,build_org_reports,filter_org_reports,@@ -159,7 +159,7 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateRtotal_orgs_with_usage = len(orgs_with_usage)sorted_reports = sort_org_reports(orgs_with_usage)- batches = list(enumerate(batched(sorted_reports, CHUNK_SIZE_ORGS)))+ batches = list(enumerate([list(batch) for batch in batched(sorted_reports, CHUNK_SIZE_ORGS, strict=False)]))chunk_keys: list[str] = [chunk_key(inputs.ctx, index) for index, _ in batches]# Each chunk is an independent S3 object, so fan the encode+gzip+PUTdiff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.pyindex c5b80ebed7e2..07833d2b1323 100644--- a/posthog/temporal/usage_report/aggregator.py+++ b/posthog/temporal/usage_report/aggregator.py@@ -10,7 +10,6 @@ the per-org `count()` N+1 in the legacy helper never fires for Temporal.Activities import from here."""-import itertoolsimport dataclassesfrom collections.abc import Iterable, Iteratorfrom datetime import datetime@@ -100,18 +99,6 @@ def filter_orgs_with_usage(org_reports: dict[str, OrgReport]) -> dict[str, OrgRereturn {oid: report for oid, report in org_reports.items() if has_non_zero_usage(report)}-def batched(iterable: Iterable[Any], size: int) -> Iterator[list[Any]]:- """Local `itertools.batched` so the module stays usable on 3.11."""- if size <= 0:- raise ValueError("batch size must be positive")- it = iter(iterable)- while True:- batch = list(itertools.islice(it, size))- if not batch:- return- yield batch--def build_manifest(ctx: WorkflowContext,chunk_keys: list[str],