: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(aio): keep 20 summarization children running at all times (#107831)
Bernat Torres7fd905199fe0
diff --git a/posthog/temporal/ai_observability/team_discovery.py b/posthog/temporal/ai_observability/team_discovery.pyindex ddeac4e1c27c..17c1e1ff2c25 100644--- a/posthog/temporal/ai_observability/team_discovery.py+++ b/posthog/temporal/ai_observability/team_discovery.py@@ -209,8 +209,9 @@ async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput | None =# Guaranteed teams first: the coordinator processes teams in this order and# may exhaust its run budget before reaching the tail, so allowlisted teams- # must never sit behind the sampled set.- discovered = sorted(guaranteed - skip) + sorted(sampled)+ # must never sit behind the sampled set. The sampled set keeps its random+ # order, so a run that stops early skips different teams each hour.+ discovered = sorted(guaranteed - skip) + sampleddiscovery_context = {"ai_event_teams_count": len(ai_event_teams),"remaining_count": len(remaining),diff --git a/posthog/temporal/ai_observability/test_team_discovery.py b/posthog/temporal/ai_observability/test_team_discovery.pyindex 06a8ac570fa9..a0e5221fd63f 100644--- a/posthog/temporal/ai_observability/test_team_discovery.py+++ b/posthog/temporal/ai_observability/test_team_discovery.py@@ -205,14 +205,16 @@ class TestGetTeamIdsForAIObservability:async def test_guaranteed_teams_ordered_before_sampled(self, mock_get_teams, mock_ff):# High guaranteed id placed ahead of a lower sampled id proves ordering is by# guaranteed-first, not global sort — the coordinator must reach allowlisted- # teams before it exhausts its run budget on the sampled tail.+ # teams before it exhausts its run budget on the sampled tail. The sampled tail+ # keeps the order random.sample returned, so the tail is not always the newest teams.mock_ff.return_value = {"guaranteed_team_ids": [9000], "sample_percentage": 1.0}mock_get_teams.return_value = [5555, 3333, 7777]inputs = TeamDiscoveryInput()- result = await get_team_ids_for_ai_observability(inputs)+ with patch("posthog.temporal.ai_observability.team_discovery.random.sample", return_value=[7777, 3333, 5555]):+ result = await get_team_ids_for_ai_observability(inputs)- assert result == [9000, 3333, 5555, 7777]+ assert result == [9000, 7777, 3333, 5555]@patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events")async def test_zero_sample_returns_only_guaranteed(self, mock_get_teams, mock_ff):diff --git a/posthog/temporal/ai_observability/trace_summarization/README.md b/posthog/temporal/ai_observability/trace_summarization/README.mdindex f9af690979d1..42336773c905 100644--- a/posthog/temporal/ai_observability/trace_summarization/README.md+++ b/posthog/temporal/ai_observability/trace_summarization/README.md@@ -58,6 +58,14 @@ Both activities are unified — they handle trace-level and generation-level sum### Coordinator: `llma-trace-summarization-coordinator`Discovers teams dynamically via `get_team_ids_for_ai_observability` (guaranteed teams + a random sample of teams with AI events, configured in `team_discovery.py`), less the teams without AI data processing consent.+Guaranteed teams come first, and the sampled teams keep a random order.++The coordinator keeps up to `max_concurrent_teams` per-team workflows running at once.+It starts the next team when any running team finishes, so one slow team holds one slot and does not delay the others.+The coordinator fixes one window from the time Temporal started the run, and passes it to every per-team workflow as `window_start` and `window_end`.+So each team covers the same hour however late in the run it starts, and consecutive runs cover consecutive hours.+Continue-as-new carries the remaining teams and the window into the next run, so it loses nothing.+A run that is skipped, or that reaches its timeout before it reaches a team, still loses that hour for the teams it did not reach.**Inputs** (`BatchTraceSummarizationCoordinatorInputs`): `max_traces`, `batch_size`, `mode`, `window_minutes`, `model` - all optional with sensible defaults.diff --git a/posthog/temporal/ai_observability/trace_summarization/constants.py b/posthog/temporal/ai_observability/trace_summarization/constants.pyindex 6c04100426b0..2ffe1b3a22b0 100644--- a/posthog/temporal/ai_observability/trace_summarization/constants.py+++ b/posthog/temporal/ai_observability/trace_summarization/constants.py@@ -65,6 +65,9 @@ SCHEDULE_INTERVAL_HOURS = 1 # How often the coordinator runs# Coordinator concurrency settingsDEFAULT_MAX_CONCURRENT_TEAMS = 20 # Max teams to process in parallel+# The patch id keeps coordinator executions that started with fixed batches deterministic on replay.+SLIDING_WINDOW_PATCH_ID = "llma-summarization-sliding-window-2026-09"+# Timeout configuration (in seconds)SAMPLE_TIMEOUT_SECONDS = 900 # 15 minutes for sampling query (buffer above QUERY_ASYNC 600s ClickHouse timeout)diff --git a/posthog/temporal/ai_observability/trace_summarization/coordinator.py b/posthog/temporal/ai_observability/trace_summarization/coordinator.pyindex 0e3eff476e63..451ea1d906d7 100644--- a/posthog/temporal/ai_observability/trace_summarization/coordinator.py+++ b/posthog/temporal/ai_observability/trace_summarization/coordinator.py@@ -4,22 +4,26 @@ Coordinator workflow for batch trace summarization.This workflow discovers teams dynamically via the team discovery activityand spawns child workflows to process traces for each team.-Uses continue_as_new after each batch to keep the workflow history bounded-(Temporal has a 50K event limit per execution).+Uses continue_as_new between teams, when Temporal suggests it, to keep the+workflow history bounded (Temporal has a 50K event limit per execution).Per-team child workflows handle the case where a team has no tracesgracefully (returning empty results).-Teams are processed in parallel batches (default 20 at a time) using-start_child_workflow + await pattern for controlled concurrency.+Teams are processed through a sliding window: up to max_concurrent_teams+children (default 20) run at once, and the next team starts as soon as any+child finishes. Every child in one run summarizes the same time window,+fixed from the time Temporal started the run."""+import asyncioimport dataclasses-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import Anyimport structlogimport temporalio+from temporalio.exceptions import ApplicationErrorfrom temporalio.workflow import ChildWorkflowHandlefrom posthog.temporal.ai_observability.trace_summarization import constants@@ -32,7 +36,9 @@ from posthog.temporal.ai_observability.trace_summarization.constants import (DEFAULT_MODE,DEFAULT_MODEL,DEFAULT_WINDOW_MINUTES,+ DEFAULT_WINDOW_OFFSET_MINUTES,GENERATION_CHILD_WORKFLOW_ID_PREFIX,+ SLIDING_WINDOW_PATCH_ID,WORKFLOW_EXECUTION_TIMEOUT_MINUTES,)from posthog.temporal.ai_observability.trace_summarization.models import (@@ -83,7 +89,7 @@ def _empty_summarization_results() -> dict[str, Any]:}[email protected](frozen=True)class BatchTraceSummarizationCoordinatorInputs:"""Inputs for the coordinator workflow."""@@ -100,6 +106,21 @@ class BatchTraceSummarizationCoordinatorInputs:per_team_filters: dict[str, list[dict[str, Any]]] | None = Noneper_team_jobs: dict[str, list[dict[str, Any]]] | None = Noneresults_so_far: dict[str, Any] | None = None+ window_start: str | None = None+ window_end: str | None = None+++def _with_summarization_window(+ inputs: BatchTraceSummarizationCoordinatorInputs, run_start: datetime+) -> BatchTraceSummarizationCoordinatorInputs:+ """Set the window every child of a run summarizes, offset so traces have time to complete."""+ window_end = run_start - timedelta(minutes=DEFAULT_WINDOW_OFFSET_MINUTES)+ window_start = window_end - timedelta(minutes=inputs.window_minutes)+ return dataclasses.replace(+ inputs,+ window_start=window_start.strftime("%Y-%m-%dT%H:%M:%SZ"),+ window_end=window_end.strftime("%Y-%m-%dT%H:%M:%SZ"),+ )@temporalio.workflow.defn(name=COORDINATOR_WORKFLOW_NAME)@@ -197,12 +218,109 @@ class BatchTraceSummarizationCoordinatorWorkflow(PostHogWorkflow):results_so_far = _empty_summarization_results()- # Phase B: process teams in batches, using continue_as_new to keep- # the workflow history bounded.+ # Phase B: dispatch the teams, using continue_as_new to keep the+ # workflow history bounded.child_id_prefix = (GENERATION_CHILD_WORKFLOW_ID_PREFIX if inputs.analysis_level == "generation" else CHILD_WORKFLOW_ID_PREFIX)+ if temporalio.workflow.patched(SLIDING_WINDOW_PATCH_ID):+ # With no slot the dispatch loop would wait forever without starting a child.+ if inputs.max_concurrent_teams < 1:+ raise ApplicationError(+ f"max_concurrent_teams must be at least 1, got {inputs.max_concurrent_teams}",+ non_retryable=True,+ )+ if not (inputs.window_start and inputs.window_end):+ # workflow_start_time, not start_time: a worker can pick the run up late, for+ # example during a deploy, and that must not shift the hour the run covers.+ inputs = _with_summarization_window(inputs, temporalio.workflow.info().workflow_start_time)+ await self._dispatch_sliding_window(+ inputs, team_ids, per_team_jobs, per_team_filters, results_so_far, child_id_prefix+ )+ else:+ await self._dispatch_batches(+ inputs, team_ids, per_team_jobs, per_team_filters, results_so_far, child_id_prefix+ )++ # Final leg: return accumulated results+ total_teams = results_so_far["teams_succeeded"] + results_so_far["teams_failed"]+ logger.info(+ "Batch trace summarization coordinator completed",+ teams_processed=total_teams,+ teams_succeeded=results_so_far["teams_succeeded"],+ teams_failed=results_so_far["teams_failed"],+ total_items=results_so_far["total_items"],+ total_summaries=results_so_far["total_summaries"],+ )++ return CoordinatorResult(+ teams_processed=total_teams,+ teams_failed=results_so_far["teams_failed"],+ failed_team_ids=results_so_far["failed_team_ids"],+ total_items=results_so_far["total_items"],+ total_summaries=results_so_far["total_summaries"],+ )++ async def _dispatch_sliding_window(+ self,+ inputs: BatchTraceSummarizationCoordinatorInputs,+ team_ids: list[int],+ per_team_jobs: dict[int, list[JobConfig]],+ per_team_filters: dict[int, list[dict[str, Any]]],+ results_so_far: dict[str, Any],+ child_id_prefix: str,+ ) -> None:+ """Keep up to max_concurrent_teams children running, so one slow team holds one slot only."""+ in_flight = 0+ pending: list[asyncio.Task[None]] = []++ async def collect(+ team_id: int, handle: ChildWorkflowHandle[BatchTraceSummarizationWorkflow, BatchSummarizationResult]+ ) -> None:+ nonlocal in_flight+ try:+ await self._collect_child_result(team_id, handle, results_so_far, inputs.analysis_level)+ finally:+ in_flight -= 1++ def has_free_slot() -> bool:+ return in_flight < inputs.max_concurrent_teams++ def is_drained() -> bool:+ return in_flight == 0++ for index, team_id in enumerate(team_ids):+ if index > 0 and temporalio.workflow.info().is_continue_as_new_suggested():+ # Children close with this run, so let the running ones finish first.+ await temporalio.workflow.wait_condition(is_drained)+ logger.info(+ "Continuing as new to keep history bounded",+ teams_remaining=len(team_ids) - index,+ teams_processed_this_leg=index,+ )+ self._continue_as_new(inputs, team_ids[index:], per_team_jobs, per_team_filters, results_so_far)++ level_jobs = self._level_jobs(inputs, team_id, per_team_jobs, per_team_filters)+ for job in level_jobs:+ await temporalio.workflow.wait_condition(has_free_slot)+ handle = await self._start_child(inputs, team_id, job, child_id_prefix)+ in_flight += 1+ record_jobs_dispatched(1, "summarization", inputs.analysis_level)+ pending.append(asyncio.create_task(collect(team_id, handle)))++ await asyncio.gather(*pending)++ async def _dispatch_batches(+ self,+ inputs: BatchTraceSummarizationCoordinatorInputs,+ team_ids: list[int],+ per_team_jobs: dict[int, list[JobConfig]],+ per_team_filters: dict[int, list[dict[str, Any]]],+ results_so_far: dict[str, Any],+ child_id_prefix: str,+ ) -> None:+ """Process fixed batches of teams. Only replays executions that started before the sliding window."""max_concurrent = inputs.max_concurrent_teamsfor batch_start in range(0, len(team_ids), max_concurrent):batch = team_ids[batch_start : batch_start + max_concurrent]@@ -212,41 +330,8 @@ class BatchTraceSummarizationCoordinatorWorkflow(PostHogWorkflow):tuple[int, ChildWorkflowHandle[BatchTraceSummarizationWorkflow, BatchSummarizationResult]]] = []for team_id in batch:- team_jobs = per_team_jobs.get(team_id, [])- level_jobs = resolve_level_jobs_for_team(- team_jobs=team_jobs,- analysis_level=inputs.analysis_level,- legacy_event_filters=per_team_filters.get(team_id, []),- )- if not level_jobs:- logger.info(- "Skipping team for analysis level with no matching summarization jobs",- team_id=team_id,- analysis_level=inputs.analysis_level,- )- continue-- for job in level_jobs:- child_suffix = f"-{team_id}-{job.job_id}" if job.job_id else f"-{team_id}"- handle = await temporalio.workflow.start_child_workflow(- BatchTraceSummarizationWorkflow.run,- BatchSummarizationInputs(- team_id=team_id,- analysis_level=inputs.analysis_level,- max_items=inputs.max_items,- batch_size=inputs.batch_size,- mode=inputs.mode,- window_minutes=inputs.window_minutes,- model=inputs.model,- event_filters=job.event_filters,- job_id=job.job_id,- job_name=job.name,- ),- id=f"{child_id_prefix}{child_suffix}-{temporalio.workflow.now().isoformat()}",- execution_timeout=timedelta(minutes=WORKFLOW_EXECUTION_TIMEOUT_MINUTES),- retry_policy=constants.COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY,- parent_close_policy=temporalio.workflow.ParentClosePolicy.TERMINATE,- )+ for job in self._level_jobs(inputs, team_id, per_team_jobs, per_team_filters):+ handle = await self._start_child(inputs, team_id, job, child_id_prefix)workflow_handles.append((team_id, handle))if workflow_handles:@@ -254,18 +339,7 @@ class BatchTraceSummarizationCoordinatorWorkflow(PostHogWorkflow):# Wait for all workflows in batch to completefor team_id, handle in workflow_handles:- try:- workflow_result: BatchSummarizationResult = await handle- results_so_far["total_items"] += workflow_result.metrics.items_queried- results_so_far["total_summaries"] += workflow_result.metrics.summaries_generated- results_so_far["teams_succeeded"] += 1- increment_team_succeeded("summarization", inputs.analysis_level)-- except Exception:- logger.exception("Failed to process team", team_id=team_id)- results_so_far["failed_team_ids"].append(team_id)- results_so_far["teams_failed"] += 1- increment_team_failed("summarization", inputs.analysis_level)+ await self._collect_child_result(team_id, handle, results_so_far, inputs.analysis_level)# After each batch, check if Temporal suggests continuing as new# to keep the history size bounded.@@ -276,40 +350,95 @@ class BatchTraceSummarizationCoordinatorWorkflow(PostHogWorkflow):teams_remaining=len(remaining),teams_processed_this_leg=batch_start + len(batch),)- # Serialize for Temporal JSON (string keys)- serializable_filters = {str(k): v for k, v in per_team_filters.items()}- serializable_jobs = {str(k): [dataclasses.asdict(j) for j in v] for k, v in per_team_jobs.items()}- temporalio.workflow.continue_as_new(- BatchTraceSummarizationCoordinatorInputs(- analysis_level=inputs.analysis_level,- max_items=inputs.max_items,- batch_size=inputs.batch_size,- mode=inputs.mode,- window_minutes=inputs.window_minutes,- model=inputs.model,- max_concurrent_teams=inputs.max_concurrent_teams,- remaining_team_ids=remaining,- per_team_filters=serializable_filters,- per_team_jobs=serializable_jobs,- results_so_far=results_so_far,- )- )+ self._continue_as_new(inputs, remaining, per_team_jobs, per_team_filters, results_so_far)- # Final leg: return accumulated results- total_teams = results_so_far["teams_succeeded"] + results_so_far["teams_failed"]- logger.info(- "Batch trace summarization coordinator completed",- teams_processed=total_teams,- teams_succeeded=results_so_far["teams_succeeded"],- teams_failed=results_so_far["teams_failed"],- total_items=results_so_far["total_items"],- total_summaries=results_so_far["total_summaries"],+ @staticmethod+ def _level_jobs(+ inputs: BatchTraceSummarizationCoordinatorInputs,+ team_id: int,+ per_team_jobs: dict[int, list[JobConfig]],+ per_team_filters: dict[int, list[dict[str, Any]]],+ ) -> list[JobConfig]:+ level_jobs = resolve_level_jobs_for_team(+ team_jobs=per_team_jobs.get(team_id, []),+ analysis_level=inputs.analysis_level,+ legacy_event_filters=per_team_filters.get(team_id, []),)+ if not level_jobs:+ logger.info(+ "Skipping team for analysis level with no matching summarization jobs",+ team_id=team_id,+ analysis_level=inputs.analysis_level,+ )+ return level_jobs- return CoordinatorResult(- teams_processed=total_teams,- teams_failed=results_so_far["teams_failed"],- failed_team_ids=results_so_far["failed_team_ids"],- total_items=results_so_far["total_items"],- total_summaries=results_so_far["total_summaries"],+ @staticmethod+ async def _start_child(+ inputs: BatchTraceSummarizationCoordinatorInputs,+ team_id: int,+ job: JobConfig,+ child_id_prefix: str,+ ) -> ChildWorkflowHandle[BatchTraceSummarizationWorkflow, BatchSummarizationResult]:+ child_suffix = f"-{team_id}-{job.job_id}" if job.job_id else f"-{team_id}"+ return await temporalio.workflow.start_child_workflow(+ BatchTraceSummarizationWorkflow.run,+ BatchSummarizationInputs(+ team_id=team_id,+ analysis_level=inputs.analysis_level,+ max_items=inputs.max_items,+ batch_size=inputs.batch_size,+ mode=inputs.mode,+ window_minutes=inputs.window_minutes,+ model=inputs.model,+ window_start=inputs.window_start,+ window_end=inputs.window_end,+ event_filters=job.event_filters,+ job_id=job.job_id,+ job_name=job.name,+ ),+ id=f"{child_id_prefix}{child_suffix}-{temporalio.workflow.now().isoformat()}",+ execution_timeout=timedelta(minutes=WORKFLOW_EXECUTION_TIMEOUT_MINUTES),+ retry_policy=constants.COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY,+ parent_close_policy=temporalio.workflow.ParentClosePolicy.TERMINATE,+ )++ @staticmethod+ async def _collect_child_result(+ team_id: int,+ handle: ChildWorkflowHandle[BatchTraceSummarizationWorkflow, BatchSummarizationResult],+ results_so_far: dict[str, Any],+ analysis_level: AnalysisLevel,+ ) -> None:+ try:+ workflow_result: BatchSummarizationResult = await handle+ results_so_far["total_items"] += workflow_result.metrics.items_queried+ results_so_far["total_summaries"] += workflow_result.metrics.summaries_generated+ results_so_far["teams_succeeded"] += 1+ increment_team_succeeded("summarization", analysis_level)++ except Exception:+ logger.exception("Failed to process team", team_id=team_id)+ results_so_far["failed_team_ids"].append(team_id)+ results_so_far["teams_failed"] += 1+ increment_team_failed("summarization", analysis_level)++ @staticmethod+ def _continue_as_new(+ inputs: BatchTraceSummarizationCoordinatorInputs,+ remaining: list[int],+ per_team_jobs: dict[int, list[JobConfig]],+ per_team_filters: dict[int, list[dict[str, Any]]],+ results_so_far: dict[str, Any],+ ) -> None:+ # Serialize for Temporal JSON (string keys)+ serializable_filters = {str(k): v for k, v in per_team_filters.items()}+ serializable_jobs = {str(k): [dataclasses.asdict(j) for j in v] for k, v in per_team_jobs.items()}+ temporalio.workflow.continue_as_new(+ dataclasses.replace(+ inputs,+ remaining_team_ids=remaining,+ per_team_filters=serializable_filters,+ per_team_jobs=serializable_jobs,+ results_so_far=results_so_far,+ ))diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.pyindex 42b6dc27c699..04f1a3db3614 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_coordinator.py@@ -1,23 +1,114 @@"""Tests for batch trace summarization coordinator workflow."""+import uuid+from datetime import datetime, timedelta+from typing import Any+import pytest-from posthog.temporal.ai_observability.shared_activities import JobConfig, resolve_level_jobs_for_team+from temporalio import activity, workflow+from temporalio.client import WorkflowFailureError+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.temporal.ai_observability.shared_activities import (+ FetchAllClusteringFiltersInput,+ FetchAllClusteringJobsInput,+ JobConfig,+ resolve_level_jobs_for_team,+)+from posthog.temporal.ai_observability.team_discovery import TeamDiscoveryInputfrom posthog.temporal.ai_observability.trace_summarization.constants import (DEFAULT_BATCH_SIZE,DEFAULT_MAX_ITEMS_PER_WINDOW,DEFAULT_MODE,DEFAULT_MODEL,DEFAULT_WINDOW_MINUTES,+ WORKFLOW_NAME,)from posthog.temporal.ai_observability.trace_summarization.coordinator import (BatchTraceSummarizationCoordinatorInputs,BatchTraceSummarizationCoordinatorWorkflow,_empty_summarization_results,)+from posthog.temporal.ai_observability.trace_summarization.models import (+ BatchSummarizationInputs,+ BatchSummarizationMetrics,+ BatchSummarizationResult,+ CoordinatorResult,+)from products.ai_observability.backend.summarization.models import SummarizationMode+SLOW_TEAM_ID = 1+DISCOVERED_TEAM_IDS = [SLOW_TEAM_ID, 2, 3, 4, 5]++child_runs: list[dict[str, Any]] = []++[email protected](name=WORKFLOW_NAME)+class FakeTeamSummarizationWorkflow:+ @workflow.run+ async def run(self, inputs: BatchSummarizationInputs) -> BatchSummarizationResult:+ started = workflow.now()+ await workflow.sleep(timedelta(minutes=10 if inputs.team_id == SLOW_TEAM_ID else 1))+ if not workflow.unsafe.is_replaying():+ child_runs.append(+ {+ "team_id": inputs.team_id,+ "window": (inputs.window_start, inputs.window_end),+ "started": started,+ "finished": workflow.now(),+ }+ )+ return BatchSummarizationResult(+ batch_run_id=str(inputs.team_id), metrics=BatchSummarizationMetrics(items_queried=1, summaries_generated=1)+ )++[email protected](name="get_team_ids_for_llm_analytics")+async def fake_team_discovery(inputs: TeamDiscoveryInput | None = None) -> list[int]:+ return DISCOVERED_TEAM_IDS++[email protected](name="fetch_all_clustering_jobs_activity")+async def fake_fetch_jobs(inputs: FetchAllClusteringJobsInput) -> dict[int, list[JobConfig]]:+ return {}++[email protected](name="fetch_all_clustering_filters_activity")+async def fake_fetch_filters(inputs: FetchAllClusteringFiltersInput) -> dict[int, list[dict[str, Any]]]:+ return {}+++async def _run_coordinator(inputs: BatchTraceSummarizationCoordinatorInputs) -> CoordinatorResult:+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[BatchTraceSummarizationCoordinatorWorkflow, FakeTeamSummarizationWorkflow],+ activities=[fake_team_discovery, fake_fetch_jobs, fake_fetch_filters],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ return await env.client.execute_workflow(+ BatchTraceSummarizationCoordinatorWorkflow.run,+ inputs,+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ execution_timeout=timedelta(minutes=55),+ )+++def _max_overlap(runs: list[dict[str, Any]]) -> int:+ edges: list[tuple[datetime, int]] = [(r["started"], 1) for r in runs] + [(r["finished"], -1) for r in runs]+ running = peak = 0+ for _, delta in sorted(edges, key=lambda edge: (edge[0], edge[1])):+ running += delta+ peak = max(peak, running)+ return peak+class TestBatchTraceSummarizationCoordinatorWorkflow:"""Tests for BatchTraceSummarizationCoordinatorWorkflow."""@@ -176,3 +267,29 @@ class TestBatchTraceSummarizationCoordinatorWorkflow:)assert [job.job_id for job in result] == expected_job_ids++ @pytest.mark.asyncio+ async def test_sliding_window_does_not_hold_teams_behind_a_slow_team(self):+ child_runs.clear()+ result = await _run_coordinator(BatchTraceSummarizationCoordinatorInputs(max_concurrent_teams=2))++ runs_by_team = {run["team_id"]: run for run in child_runs}+ assert result.teams_processed == len(DISCOVERED_TEAM_IDS)+ assert result.teams_failed == 0+ assert sorted(runs_by_team) == sorted(DISCOVERED_TEAM_IDS)+ assert _max_overlap(child_runs) == 2+ assert all(run["finished"] <= runs_by_team[SLOW_TEAM_ID]["finished"] for run in child_runs)+ windows = {run["window"] for run in child_runs}+ assert len(windows) == 1+ assert None not in next(iter(windows))++ @pytest.mark.asyncio+ @pytest.mark.parametrize("max_concurrent_teams", [0, -1])+ async def test_non_positive_concurrency_fails_instead_of_hanging(self, max_concurrent_teams):+ child_runs.clear()+ with pytest.raises(WorkflowFailureError) as exc_info:+ await _run_coordinator(BatchTraceSummarizationCoordinatorInputs(max_concurrent_teams=max_concurrent_teams))++ assert isinstance(exc_info.value.cause, ApplicationError)+ assert "max_concurrent_teams" in str(exc_info.value.cause)+ assert child_runs == []